首页 > 解决方案 > 如何将变量 (sFolder) 从 CommandButton1_Click 传递/存储到 Commandbutton2_Click?

问题描述

由建立后,"sFolder"变量不显示。CommandButton2_Click()CommanButton1_Click()

我试过调用不同的 subs 并传递变量,但我无法得到正确的组合。

Public Sub CommandButton1_Click()
Dim sFolder As Variant
If sFolder = "" Then
With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Select a Folder"
    If .Show = -1 Then
        sFolder = .SelectedItems(1)
    End If
End With
End Sub

Sub CommandButton2_Click()
Debug.Print sFolder
End Sub

我希望第二个按钮打印我选择的文件名,但它是空白的,没有错误。

标签: excelvbacallcommandbutton

解决方案


它不是空白,而是Variant/Empty,这是您为任何未初始化/未声明的局部变量获得的变体子类型 -Option Explicit通过强制您声明您正在使用的变量来阻止某些事情。

sFolder只存在于过程的范围内:它在(或其他任何地方)CommandButton1_Click的范围内是未定义的。CommandButton2_Click

Option Explicit在模块顶部指定,并将该sFolder变量从局部变量提升为模块变量(从 button1 单击处理程序中删除Dim sFolder As Variant声明),以便它现在可用于该模块的每个过程:

Option Explicit
Private sFolder As Variant

现在,如果您首先单击 button2,您仍然会得到一个空字符串(因为字符串表示Variant/Empty是一个空字符串),但是如果您在单击 button1 后单击 button2,您将在即时窗格中看到该值。


推荐阅读