时间:2019-01-31 06:35:40

标签: excel vba

编辑我忘了提到该错误发生在.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

我希望当用户保存文档时宏会激活,但是会弹出此错误,阻止这样做。

1 个答案:

答案 0 :(得分:0)

请检查路径分隔符(斜杠或反斜杠):

Debug.Print "Application.PathSeparator: ", Application.PathSeparator

请尝试打开它,否则尝试使用完整路径。

On Error Resume Next
Set wbOut = Workbooks("ValveStockMaster.xlsx") ' already open?
If Err.Number <> 0 Then
    On Error Goto 0
    ' use full path:
    Set wbOut = Workbooks.Open("C:\Users\MathieuKlein\Desktop\ValveStockMaster.xlsx")
    ' ...
End If
On Error Goto 0
' ...

请这样声明:

' instead of Dim wbMe, wbOut As Workbook
Dim wbMe As Workbook, wbOut As Workbook

如果以后没有将其放置在某人的桌面上,请尝试使用以下路径之一连接。 G。像Application.DefaultFilePath & "\Test.xlsx"

Debug.Print "ActiveWorkbook.Path: ", ActiveWorkbook.Path
Debug.Print "ThisWorkbook.Path: ", ThisWorkbook.Path
Debug.Print "Application.DefaultFilePath: ", Application.DefaultFilePath
Debug.Print "Application.RecentFiles(1).Path: ", Application.RecentFiles(1).Path
Debug.Print "Path: ", Application.Path
Debug.Print "LibraryPath: ", Application.LibraryPath
Debug.Print "StartupPath: ", Application.StartupPath
Debug.Print "AltStartupPath: ", Application.AltStartupPath 
Debug.Print "AutoRecover.Path: ", Application.AutoRecover.Path
Debug.Print "TemplatesPath: ", Application.TemplatesPath
Debug.Print "UserLibraryPath: ", Application.UserLibraryPath