excel - 如何将变量 (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
我希望第二个按钮打印我选择的文件名,但它是空白的,没有错误。
解决方案
它不是空白,而是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,您将在即时窗格中看到该值。
推荐阅读
- javascript - 如何在 Typescript 中验证数组为空
- javascript - p5.js:随机颜色并保存为 pdf 功能
- java - 对齐缩进
- rules - 规则不执行
- function - 谁能弄清楚如何测试这个 OCAML 功能?
- linux - 文件更改时自动重启服务器
- sql - Distinct vs row_number() - 使用相同条件的查询在oracle中给出不同的结果?
- c++ - 防止递归组合生成中的内存分配
- distributed-computing - paxos 是否提供真正的线性化一致性?
- mysql - SQL:在最短的 300 次行程中,这些骑手中有多少是孩子