Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

excel

vba

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
like image 915
Zack Withrow Avatar asked Feb 10 '16 15:02

Zack Withrow


People also ask

What does invalid outside procedure mean in VBA?

means that you have to declare all variables that you use; referring to an undeclared variable will cause an error. Next, you can declare variables and constants (and some other things) that can be used throughout the code module (or even in all modules in the same workbook). For example: Const MyName="JeanMarie"

How do I bypass VBA error in Excel?

If you want to ignore the error message only for a specific set of code, then close the on error resume next statement by adding the “On Error GoTo 0” statement.

What is an invalid qualifier in VBA?

Qualifiers are used for disambiguation. This error has the following cause and solution: The qualifier does not identify a project, module, object, or a variable of user-defined type within the current scope.


1 Answers

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

like image 86
Michael Liu Avatar answered Feb 20 '23 02:02

Michael Liu