Vba Visual Basic中定义的错误

Vba Visual Basic中定义的错误,vba,Vba,当我使用这个const语句时,我的编码工作得很好 Const strFullName As String = "C:\Sample\Haha.txt" 在我更改Search.text(Textbox名称)后,它会继续显示错误 Const strFullName As String = "C:\Sample\" & Search.Text & ".txt" 编译错误: 需要常量表达式 然后我尝试创建一个textbox1.text=Searchbox.text。文本框1显示C:\

当我使用这个const语句时,我的编码工作得很好

Const strFullName As String = "C:\Sample\Haha.txt"
在我更改Search.text(Textbox名称)后,它会继续显示错误

Const strFullName As String = "C:\Sample\" & Search.Text & ".txt"
编译错误:

需要常量表达式

然后我尝试创建一个textbox1.text=Searchbox.text。文本框1显示C:\Sample\Haha.txt


请提供帮助,谢谢~

搜索。文本
不是常量-它是一个运行时属性,在运行时之前它的值是未知的,因此无法将其分配给常量。您可以将strFullName定义为变量而不是常量:

Dim strFullName As String

...
' Set strFullName at run-time
strFullName = "C:\Sample\" & Search.Text & ".txt"

如果
Search
是一个文本框,您可能还需要检查它是否有有效的输入,以确保您没有试图形成无效的文件名;例如,您可以使用
Len(Search.Text)
来确定文本框中文本的长度。

正如错误所述,将值赋给常数时,必须使用文字值-不能将变量作为表达式的一部分来计算值。使用字符串变量代替。除了常量定义,还有什么可以使用?太好了!!谢谢你的建议。非常感谢:DOr只需检查以确保
Len(Dir(strFullName))0
,这将有助于确保您不会收到格式错误的文件路径。