VSTO & .NET & Excel

October 6, 2011

Evaluate Sheet Types & Copy Sheets with VB

Filed under: .NET & Excel, Excel — Dennis M Wallentin @ 2:47 pm

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:= _


End If


With xlApp
.Visible = True
.UserControl = True
End With

'Don't forget to clean up properly.

End Sub

Kind regards.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: