使用 Dim 时外部程序无效

invalid outside procedure when using Dim

我收到以下代码的 "invalid outside procedure" 错误。谁能告诉我哪里出了问题。

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

确保您可以 运行 多个 Sub 中的代码的最佳方法是将其设为 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

当你想在别处执行这段代码时,你应该使用:

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