为什么我的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 

Set程序不允许Set语句。 将Set语句移到Formatting过程中:

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

(我将Dim语句也移到了程序中,我希望尽可能避免使用全局variables。)

您可以将variables声明为全局variables,但不能将它们设置为诸如子或函数之类的过程之外。

如果您需要将此variables作为全局variables,那么最好将其设置为开启。 Workbook_Open()

如果你不需要它作为一个全局的话,那么把声明和设置语句都移到你的程序中