为什么我的VBA代码抛出一个;“外部程序无效”;错误?

为什么我的VBA代码抛出一个;“外部程序无效”;错误?,vba,excel,Vba,Excel,就我个人而言,我无法理解为什么下面的代码会抛出一个编译错误,并显示消息“invalideoutprocedure”。它在下面的星号线上突出显示错误 Option Explicit Dim shtThisSheet As Worksheets **Set shtThisSheet = Application.Workbook("Formatting2.xlsm").Worksheets("Sheet1")** Sub Formatting() With shtThisSheet

就我个人而言,我无法理解为什么下面的代码会抛出一个编译错误,并显示消息“invalideoutprocedure”。它在下面的星号线上突出显示错误

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

Set
语句不允许出现在过程之外。将
Set
语句移动到
格式化过程中:

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

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

您可以将变量声明为全局变量,但不能在子过程或函数等过程之外设置它们

如果您需要将此变量作为全局变量,那么最好将其设置为启用。 工作簿_Open()


如果不需要将其作为全局对象,则将声明和set语句都移动到过程中

同时尝试将其暗显到集合(工作表)而不是对象(工作表),同时也将其与SHTTThisSheet一起使用
,但不在
范围
语句中引用。您应该改用
.Range
。这解决了旧问题(谢谢),您知道为什么它会导致脚本超出范围错误吗?设置shtThisSheet=Application.Workbooks(“Formatting2.xlsm”)。工作表(“Sheet1”)可能找不到名为Formatting2.xlsm的打开工作簿,或者在该工作簿中找不到名为Sheet1的工作表。