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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35319309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:12:56  来源:igfitidea点击:

Why does my VBA code throw an "Invalid outside procedure" error?

excelvbaexcel-vba

提问by Zack Withrow

For the life of me I cannot figure out why the following code is throwing a compile error with the message "Invalid outside procedure". It is highlighting the error on the starred line below.

在我的一生中,我无法弄清楚为什么以下代码会抛出带有“无效的外部过程”消息的编译错误。它突出显示了下面带星号的行上的错误。

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

回答by Michael Liu

Setstatements aren't allowed outside procedures. Move the Setstatement into the Formattingprocedure:

Set不允许在程序之外使用语句。将Set语句移到Formatting过程中:

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

(I'd move the Dimstatement into the procedure as well. I prefer to avoid global variables when possible.)

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

回答by Zack Withrow

You can declare variables as global, but you cannot set them outside of a procedure such as a sub or function.

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

If you need this variable as a global, then it's best to set it on. Workbook_Open()

如果您需要将此变量作为全局变量,那么最好将其设置为 on。工作簿_打开()

If you do not need it as a global, then move both the declaration and the set statement into your procedure

如果您不需要它作为全局,那么将声明和 set 语句移到您的过程中