Efe
Efe

Reputation: 954

invalid outside procedure when using Dim

I get "invalid outside procedure" error with the following code. Could someone please tell me where I go wrong here.

Dim Asset As String, AssetURL As String

Asset = Range("B1").Value

If Asset = "1" Then
    AssetURL = "X:\Docs\excel0001.xls"
Elseif Asset = "2" Then
    AssetURL = "X:\Docs\excel0002.xls"
End If

Range("C1").Value = AssetURL

Upvotes: 1

Views: 173

Answers (1)

Gary's Student
Gary's Student

Reputation: 96753

The best way to ensure you can run your code within multiple Subs is to make it a Public Sub:

Public Sub qwerty()
    Dim Asset As String, AssetURL As String

    Asset = Range("B1").Value

    If Asset = "1" Then
        AssetURL = "X:\Docs\excel0001.xls"
    ElseIf Asset = "2" Then
        AssetURL = "X:\Docs\excel0002.xls"
    End If

    Range("C1").Value = AssetURL
End Sub

When you want to execute this code elsewhere, you should use:

Sub OtherSub()
    'OtherSub Code
    Call qwerty() 'or just qwerty
    'Rest of OtherSub Code
End Sub

Related question on using Call to utilize a Sub within another Sub

Upvotes: 5

Related Questions