为什么我的VBA代码会抛出"无效的外部过程"错误?

Zac*_*row 4 excel vba excel-vba

对于我的生活,我无法弄清楚为什么以下代码抛出编译错误消息"无效的外部过程".它突出显示下面的星号线上的错误.

Option Explicit

Dim shtThisSheet As Worksheets

**Set shtThisSheet = Application.Workbook("Formatting2.xlsm").Worksheets("Sheet1")**

Sub Formatting()

    With shtThisSheet

        With Range("A1")
            .Font.Bold = True
            .Font.Size = 14
            .HorizontalAlignment = xlLeft
        End With

        With Range("A3:A6")
            .Font.Bold = True
            .Font.Italic = True
            .Font.ColorIndex = 5
            .InsertIndent 1
        End With

        With Range("B2:D2")
            .Font.Bold = True
            .Font.Italic = True
            .Font.ColorIndex = 5
            .HorizontalAlignment = xlRight
        End With

        With Range("B3:D6")
            .Font.ColorIndex = 3
            .NumberFormat = "$#,##0"
        End With

    End With

End Sub
Run Code Online (Sandbox Code Playgroud)

Mic*_*Liu 8

Set外部程序不允许声明.将Set语句移动到Formatting过程中:

Sub Formatting()
    Set shtThisSheet = Application.Workbook("Formatting2.xlsm").Worksheets("Sheet1")
    ...
Run Code Online (Sandbox Code Playgroud)

(我也会将Dim语句移到程序中.我希望尽可能避免使用全局变量.)