Zack Withrow
Zack Withrow

Reputation: 125

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

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

Upvotes: 7

Views: 92824

Answers (2)

user5889203
user5889203

Reputation:

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()

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

Upvotes: 3

Michael Liu
Michael Liu

Reputation: 55419

Set statements aren't allowed outside procedures. Move the Set statement into the Formatting procedure:

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

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

Upvotes: 13

Related Questions