我一直在研究一个小宏但遇到了错误。 宏的功能如下:现有工作表中有一个库存清单。宏进入文件夹并打开存储建议的电子表格。然后返回原始工作表,获取每个股票代码,然后进入推荐表,看看是否有相应的股票及其推荐。
代码工作正常,但是当我试图让宏切换它需要处理哪个工作簿时,我现在得到一个VBA运行时错误438。
错误发生在application.wb2.activate
行上,然后再次降低application.wb2.activate
和application.wb.activate
当我用完整目录替换wb和wb2时,即H:\ A \ AA \ recommendations.xlsx和H:\ A \ AA \ nnovember 2017.xlsm,它可以正常工作。
感谢您的帮助!谢谢!
Option Explicit
Option Compare Text
Sub gsr()
Dim firstrow As Integer, lastrow As Integer, i As Integer
Dim gsr As Range, msr As Range
Dim stock, findstock As Range, col As Integer
Dim sPath As String, sFile As String
Dim sPath2 As String, sFile2 As String
Dim wb As Workbook, wb2 As Workbook
Dim xlrange As Range, xlcell As Range, xlsheet As Worksheet
Dim xllastrow As Integer
Dim foundlocationG As String, foundlocationM As String
With ActiveWorkbook
sPath2 = ActiveWorkbook.Path & "\"
sFile2 = sPath2 & ActiveWorkbook.Name
Set wb2 = ActiveWorkbook
End With
sPath = "H:\A\AA\"
sFile = sPath & "Recommendations.xlsx"
Set wb = Workbooks.Open(sFile)
Set xlsheet = Sheets("Sheet1")
xllastrow = xlsheet.Range("A1").End(xlDown).Row
Set xlrange = xlsheet.Range("A1:A" & xllastrow)
Application.wb2.Activate
With wb2.Sheets("Sheet1").Range("A:Z")
Set stock = .Find(what:="Stock", After:=.Cells(.Cells.Count), LookIn:=xlValues, Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
Set gsr = .Find(what:="GS", After:=.Cells(.Cells.Count), LookIn:=xlValues, Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
Set msr = .Find(what:="MS", After:=.Cells(.Cells.Count), LookIn:=xlValues, Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
firstrow = stock.Row + 1
lastrow = .Cells(.Rows.Count, stock.Column).End(xlUp).Row
lastrow = lastrow - 1
col = stock.Column
For i = firstrow To lastrow
For Each xlcell In xlrange
If xlcell.Value = Cells(i, col) Then
Application.wb.Activate
foundlocationG = Cells(xlcell.Row, 2)
foundlocationM = Cells(xlcell.Row, 3)
Application.wb2.Activate
Cells(i, gsr.Column) = foundlocationG
Cells(i, msr.Column) = foundlocationM
End If
Next xlcell
Next i
End With
End Sub
答案 0 :(得分:1)
您似乎混淆了Workbook.Activate和Application.Activate¹方法。
Activate是Workbook对象的直接方法。如果您已将对象级变量(例如 Set )正确分配给Workbook object,则应该可以直接调用Activate方法。
解决方案:删除应用程序,只需从指定的对象变量中激活打开的工作簿。
wb2.Activate
...
wb.Activate
出于所有意图和目的,不必像以前那样激活工作簿,也不是更有效的代码。有关详细信息,请参阅How to avoid using Select in Excel VBA。
¹ Application.Activate在Word VBA项目中更常用。