VBA运行时错误438

我一直在研究一个小macros,但遇到了一个错误。 macros的function如下:在现有工作表中有一个库存清单。 macros进入文件夹并打开存储build议的电子表格。 然后回到原来的表格,拿出每个股票代码,然后进入build议表,看看是否有相应的股票,以及它的推荐是什么。

代码工作正常,但是我现在得到一个VBA运行时错误438,当我试图让macros切换它需要工作的工作簿。

该错误发生在行application.wb2.activate ,然后再降低与application.wb2.activateapplication.wb.activate

当我用完整目录replacewb和wb2时,即H:\ A \ AA \ recommendations.xlsx和H:\ A \ AA \ 2017年11月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 

你似乎混淆了Workbook.Activate和Application.Activate方法。

Activate是Workbook对象的直接方法。 如果你已经正确地赋予(例如Set )一个对象级variables给Workbook对象 ,你应该可以直接调用Activate方法。

解决scheme:删除应用程序,并从分配的对象variables中激活打开的工作簿。

 wb2.Activate ... wb.Activate 

对于所有的意图和目的,如你所做的那样激活工作簿是没有必要的,并不是更高效的代码。 有关更多信息,请参阅如何避免在Excel VBA中使用select 。

¹Application.Activate 在Word VBA项目中更常用。