我一直在这一天工作,似乎无法弄清楚。这就是我要做的(应该是很简单):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 –