This post demonstrate how we can evaluate sheet types and how to copy sheets with VB. In other words, no rocket science.
The following procedure is only for demonstration purpose. It shows how easy it is to evaluate what sheet types we have. It also demonstrate how to dimension an object array and how to populate it at run time.
Bear in mind that Excel assume the sheet’s name to copy is part of an object array.
Private Sub btnCopy_Sheets_Click(sender As System.Object, _ e As System.EventArgs) _ Handles btnCopy_Sheets.Click Const Path As String = _ "c:\Users\Dennis Wallentin\Documents\Data\" Dim wbObject As Excel.Workbook = Nothing Dim oSheetName(0) As Object Dim xlApp As Excel.Application = New Excel.Application Dim wbTarget As Excel.Workbook = _ xlApp.Workbooks.Open(Path + "Target.xlsx") With xlApp .Workbooks.Open(Path + "DT1.xlsx") .Workbooks.Open(Path + "DT2.xlsx") End With For Each wbObject In xlApp.Workbooks If Not wbObject.Name = wbTarget.Name Then 'Check type of sheet. If TypeOf (wbObject.Sheets(1)) Is Excel.Worksheet Then Dim wks As Excel.Worksheet = _ CType(wbObject.Worksheets(1), Excel.Worksheet) 'Add value to the one-dimensional object array. oSheetName.SetValue(wks.Name.ToString(), 0) 'Just to show the Excel.Chart sheet type. ElseIf TypeOf (wbObject.Sheets(1)) Is Excel.Chart Then Dim chs As Excel.Chart = CType(wbObject.Sheets(1), Excel.Chart) 'Add value to the one-dimensional object array. oSheetName.SetValue(chs.Name.ToString(), 0) End If wbObject.Sheets(oSheetName).Copy(After:= _ wbTarget.Sheets(wbTarget.Sheets.Count)) wbObject.Close(SaveChanges:=False) End If Next With xlApp .Visible = True .UserControl = True End With 'Don't forget to clean up properly. End Sub
Kind regards.
Dennis