NET代碼(Microsoft.Office.Interop已經導入)。當我嘗試調試它時什麼都沒說,但是當我運行它時,打開2個文件(List.xls和File3.xlsm),當它到達時如果sh1.Cells(x + 1,2)<>「」那麼說InvalisCastException。 這意味着什麼?我如何修復代碼?VB .NET InvalisCastException using Microsoft.Office.Interop
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oXL As Excel.Application
Dim Wk1, Wk2, Wk3 As Excel.Workbook
Dim Sh1, Sh2, Sh3, Sh4 As Excel.Worksheet
Dim nomefile As Object, seleziona As Object
Dim x As Integer, y As Integer, v As Integer, u As Integer, w As Integer, t As Integer, z As Integer
' Start Excel and get Application object.
oXL = CreateObject("Excel.Application")
oXL.Visible = True
'set and open first Workbook
Wk1 = oXL.Workbooks.Open(Filename:="C:\xxx\List.xls")
'set and open third Workbook
Wk3 = oXL.Workbooks.Open(Filename:="C:\xxx\File3.xlsm")
'set first sheet (list.xls)
Sh1 = Wk1.Worksheets("List")
'set third sheet (File3.xlsm)
Sh3 = Wk3.Worksheets("All")
For x = 1 To 1000
**If sh1.Cells(x + 1, 2) <> "" Then**
'select filename from sh1 (list.xls)
seleziona = Sh1.Cells(x + 1, 2)
nomefile = "C:\xxx\" & Left(seleziona, 1) & "\" & seleziona & ".xls"
'set and open filename from list
Wk2 = oXL.Workbooks.Open(Filename:=nomefile)
'set second sheet (nomefile.xls)
Sh2 = Wk2.Worksheets("ESAMI")
'set forth sheet (nomefile.xls)
Sh4 = Wk2.Worksheets("Foglio3")
z = 0
y = 0
v = 1
u = 1
w = 0
t = 0
While z = 0
If sh2.Cells(1, y + 4) <> "" Then
'find empty cells on sh2 first row
y = y + 1
Else : sh2.Range(sh2.Cells(1, 4), sh2.Cells(114, (y + 4) - 1)).Copy()
'copy/paste from sh2 to sh4 of not-empty data (last not-empty row is always 114)
Sh4.Range("C1").PasteSpecial(Excel.XlPasteType.xlPasteValuesAndNumberFormats, SkipBlanks:=False, Transpose:=True)
'clear clipboard
Clipboard.Clear()
While w = 0
If Sh4.Cells(v, 3) <> "" Then
'set column 2 on sh4 equal to file's name
Sh4.Cells(v, 2) = seleziona
v = v + 1
Else : Sh4.Cells(v - 1, 1) = "u"
'find last non empty row on sh4 and put a "u" on first row
Sh4.Range(Sh4.Cells(1, 1), Sh4.Cells(v - 1, 116)).Copy()
While t = 0
If Sh3.Cells(u, 2) <> "" Then
'copy all from sh4 (nomefile.xls) to sh3 (file3.xlsm)
u = u + 1
Else
Sh3.Range(Sh3.Cells(u, 1), Sh3.Cells(u, 1)).PasteSpecial(Excel.XlPasteType.xlPasteFormulasAndNumberFormats, SkipBlanks:=False, Transpose:=False)
Clipboard.Clear()
t = 1
End If
End While
w = 1
End If
End While
z = 1
End If
End While
Clipboard.Clear()
'close opened file from list
Wk2.Close(False)
End If
Next
wk2 = Nothing
sh1 = Nothing
sh2 = Nothing
sh3 = Nothing
Wk1.Close(False)
End Sub
End Class
嘗試'sh1.Cells(x + 1,2).Value <>「」' –
只有在設置了Option Strict Off後才能使用。此外,Cells屬性返回一個「Excel.Range」對象。 – Styxxy
With .value I have:太多參數'Public Property Value([RangeValueDataType As Object])As Object' – user3023582