我一直在這一天工作,似乎無法弄清楚。這就是我要做的(應該是很簡單):VBA - 應用程序定義或對象定義錯誤?
兩個工作簿:一個已經(的ThisWorkbook)打開,一個通過Application.FileDialog(msoFileDialogOpen)開(我們將調用這個練習冊2)
- 如果列K在ThisWorkbook中爲空,「Sheet1」然後分別在工作簿2「503雜項」,列B和G中的列M和列P中搜索值。
- 如果Workbook2中的值匹配「503 Sundry」,則將H列和I列中的值複製並粘貼到ThisWorkbook中。「Sheet1」分別爲列I和K。
這是我到目前爲止,但我不斷收到錯誤消息「應用程序定義或對象定義的錯誤」下面的粗體行代碼。
Sub JPlan()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim cell1 As Range, rng1 As Range, cell2 As Range, rng2 As Range
Dim Cel As Range
Dim Sht1 As Worksheet
Dim SundrySht As Worksheet
Set wb1 = ThisWorkbook
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
If .Show Then
Filename = .SelectedItems(1)
Set wb2 = Workbooks.Open(Filename)
Else
Exit Sub
End If
End With
Set Sht1 = wb1.Sheets("Sheet1")
Set SundrySht = wb2.Sheets("503 Sundry")
Set Cel = Sht1.Range("P2")
Set rng1 = Range(Cel, Cel.Offset(Sht1.Cells.Rows.Count - Cel.Row, 0).End(xlUp))
Set Cel = SundrySht.Range("G2")
Set rng2 = Range(Cel, Cel.Offset(SundrySht.Cells.Rows.Count - Cel.Row, 0).End(xlUp))
If Sht1.Cells(i, 11) = "" Then 'if current cell in column 11 is empty then...
For Each cell2 In rng2 'for each cell in range 2 defined above (column G in "503 Sundry")...
For Each cell1 In rng1 'for each cell in range 1 defined above (column P in Sheet 1)...
If cell2.Value = cell1.Value And cell2.Offset(0, -5) = cell1.Offset(0, -3).Value Then 'if the value of cell2 equals the value of cell1 AND the value of cell2 (offset by 5 columns) equals the value of cell1 (offset by 3 columns) then...
cell1.Offset(0, -7).Value = cell2.Offset(0, 1).Value 'from to Sundry column H to Sheet1 column I
cell1.Offset(0, -5).Value = cell2.Offset(0, 2).Value 'from to Sundry column I to Sheet1 column K
Exit For
End If
Next
Next
End If
End Sub
代碼視圖做語法高亮,但是你可能已經應用的任何粗體都會丟失。你能找到一些其他方式來指出錯誤嗎? – teylyn
這裏有[938其他現有的帖子](http://stackoverflow.com/search?q=%5Bvba%5D+application+defined+or+object+defined+error),包含精確的錯誤信息。你有多少人在發佈另一篇文章之前,看過他們是否回答了你的問題? –
看起來像只在if子句的一部分中設置了wb2。如果你從未設置它,會發生什麼?最有可能的是1004錯誤lol –