如何从文本框中获取路径输入并在 vba 宏的命令按钮中使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14060079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 18:59:32  来源:igfitidea点击:

how to get path input from textbox and use in command button in vba macros

vbapathtextbox

提问by PASUMPON V N

I have textbox and command button in the form1.

我在form1中有文本框和命令按钮。

I will input path in the textbox

我将在文本框中输入路径

After the clicking the command button, workbook from the path location should open and need to the require macros code like copying , etc

单击命令按钮后,路径位置的工作簿应打开并需要复制等所需的宏代码

when i tried using the . I getting error saying that file1.xlsx not found . plz help

当我尝试使用 . 我收到错误提示 file1.xlsx not found 。请帮忙

Private Sub CommandButton1_Click()
Set wb1 = Workbooks.Open("file1")
End Sub

Private Sub TextBox1_Change()
Dim file1 As String
file1 = TextBox1.Value
End Sub

Private Sub UserForm_Click()
End Sub

回答by Alan K

The suggestions in the comments above will get you where you need to go, but if I may suggest... rather than using a textbox for the user to enter the name in, use the GetOpenFilename dialog. In this way you can ensure that the path is valid and the file actually exists. It also gives the user a nice GUI which is more like what they're used to for a File -> Open dialog. Something like this:

上面评论中的建议将使您到达需要去的地方,但如果我可以建议...而不是使用文本框供用户输入名称,请使用 GetOpenFilename 对话框。这样就可以确保路径有效并且文件确实存在。它还为用户提供了一个很好的 GUI,这更像是他们习惯的文件 -> 打开对话框。像这样的东西:

Private Sub CommandButton1_Click()

    Dim vnt As Variant

    On Error GoTo ErrorHandler

    vnt = Application.GetOpenFilename("Excel Files (*.xlsx; *.xls; *.xlsm),*.xlsx;*.xls;*.xlsm", 1, "Please select the file to open")

    If vnt = False Then Exit Sub

    Application.Workbooks.Open (vnt)

ExitPoint:

    Exit Sub

ErrorHandler:

    MsgBox "Error " & Err.Number & vbCrLf & Err.Description

    Resume ExitPoint

End Sub