Click here to Skip to main content
15,900,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When copying worksheets between workbooks in VB.net, I get this error:
Specified Cast is Not Valid

I inserted a message box MessageBox.Show(wshTest.Range("A8").Value.ToString) to verify that the worksheet being copied to the other workbook was valid. It was. I'm at my wits end.
VB
wshTest.Copy(wbkDest.Sheets())

Private Sub btnGenerateReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerateReport.Click
        Dim dpl As New List(Of DatasetPair)
        'Try
        Me.Cursor = Cursors.WaitCursor
        Dim intSheetCount As Integer = 0
        For i As Integer = 0 To lvMatchedDvid.Items.Count - 1
            Dim dp As New DatasetPair
            dp.DataVersionIdOne = lvMatchedDvid.Items(i).Text.ToString
            dp.DataVersionIdTwo = lvMatchedDvid.Items(i).SubItems(1).Text.ToString
            intSheetCount += 1
            dp.SheetId = intSheetCount
            dpl.Add(dp)
        Next

        Dim wb As Excel.Workbook = Utilities.CreateWorkbook()
        Dim strFilePath As String = wb.Path.ToString & "\" & wb.Name.ToString

        For Each dp As DatasetPair In dpl
            Dim excelApp As New Excel.Application
            Dim ws As New Excel.Worksheet
            ws = GenerateWorksheet(dp)

            Dim strSourceFilePath As String
            strSourceFilePath = wb.Path.ToString & "\" & wb.Name.ToString
            Dim wbkDest As Excel.Workbook = excelApp.Workbooks.Open(strFilePath)
            Dim wshTest As Excel.Worksheet = DirectCast(ws, Excel.Worksheet)
            Dim wbkSource As Excel.Workbook = excelApp.Workbooks.Open(strSourceFilePath)
            MessageBox.Show(wshTest.Range("A8").Value.ToString)            
            wshTest.Copy(wbkDest.Sheets())            
        Next
Posted
Updated 10-Sep-10 6:36am
v2

1 solution

My guess would be that you must use Worksheets instead of Sheets. This is because a Sheet can be more than only a Worksheet. In most cases this doesn't matter but here it might.

Try this:
wshTest.Copy(wbkDest.Worksheets())    


Good luck!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900