【发布时间】:2019-01-31 06:35:39
【问题描述】:
编辑我忘了提到错误发生在.activate 行。
我有一个简单的宏设置,可以用一些数据更新一个单独的文档。我希望宏在用户保存时自动激活,但每当我尝试使用宏时都会收到此错误“对象变量或未设置块变量”。
我在ThisWorkbook 模块中有代码。我已将代码放在一个新模块中,它工作正常,没有错误。仅当代码在 ThisWorkbook 模块中时才会出现该错误。
Option Explicit
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim wbMe, wbOut As Workbook
Application.ScreenUpdating = False
Set wbMe = ActiveWorkbook
'Sets the destination for the data as well as automatically sending the data to the sheet that corresponds with the date inputted.
Set wbOut = Workbooks.Open("/Users/MathieuKlein/Desktop/ValveStockMaster.xlsx")
'This section deals with the actual process of copying the data and pasting it to the other excel file.
With wbOut
.Activate
' The following sets up the total of valves
wbOut.Sheets("Stock").Range("D2:H20") = wbMe.Sheets("Macro Data").Range("K104:O122").Value
wbOut.Sheets("Stock").Range("D22:H37") = wbMe.Sheets("Macro Data").Range("K123:O138").Value
wbOut.Sheets("Stock").Range("D39:H46") = wbMe.Sheets("Macro Data").Range("K139:O146").Value
wbOut.Sheets("Stock").Range("D48:H50") = wbMe.Sheets("Macro Data").Range("K147:O149").Value
wbOut.Sheets("Stock").Range("D52:H53") = wbMe.Sheets("Macro Data").Range("K150:O151").Value
wbOut.Sheets("Stock").Range("D55:H58") = wbMe.Sheets("Macro Data").Range("K152:O155").Value
wbOut.Sheets("Stock").Range("D61:H61") = wbMe.Sheets("Macro Data").Range("H14,H3,H5,H7,H9").Value
End With
With wbOut
.Save
.Close
End With
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
我希望宏在用户保存文档时激活,但弹出此错误会阻止该操作。
【问题讨论】:
-
似乎回想一下工作簿是否已经打开,然后尝试使用 workbooks.open 打开同一个工作簿不会返回对该工作簿的引用。当
With运行时,wbOut是否设置为工作簿? -
我在这段代码中看不到任何会导致此错误的内容。我确实在
Sheets("Macro Data")与Sheets("Macro Data")中看到了一个可能的错字,这可能会导致错误9 下标超出范围,但不是对象变量或未设置块变量。您可能正在运行其他一些导致此问题的代码。前往the exact line 发生的地方。 -
Range("H14,H3,H5,H7,H9")联合未按该顺序传递值(如果有的话)。 -
你不能在多区域范围内使用 .Value
-
不相关但应该使用
Set wbMe = ActiveWorkbook而不是Set wbMe = ThisWorkbook