将硬编码文件路径更改为 VBA 中提示的用户?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7152660/
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-08 11:48:11  来源:igfitidea点击:

Change hardcoded file path to user prompted in VBA?

vbauser-input

提问by Shayon Saleh

Right now, I have a VBA macro for Word which parses a document for a certain font and outputs all font of the selected type to a text file.

现在,我有一个用于 Word 的 VBA 宏,它解析特定字体的文档并将所选类型的所有字体输出到文本文件。

The hard coded line which I open the text file is something like this:

我打开文本文件的硬编码行是这样的:

Open "C:\Documents and Settings\Output.txt" For Output As #n

Can I change this so the user is prompted to enter the file path at this point in the macro? Something like:

我可以更改此设置以便提示用户此时在宏中输入文件路径吗?就像是:

Open (PROMPTS USER FOR FILE PATH HERE) For Output As #n

Sorry if this seems trivial. I am new to VBA coding.

对不起,如果这看起来微不足道。我是 VBA 编码的新手。

回答by Banjoe

Two ways:

两种方式:

Simple

简单的

Dim path As String

path = InputBox("Enter a file path", "Title Here")
Open path For Output As #1
Close #1

With File Chooser

使用文件选择器

Dim path As String

With Application.FileDialog(msoFileDialogOpen)
    .Show
    If .SelectedItems.Count = 1 Then
        path = .SelectedItems(1)
    End If
End With

If path <> "" Then
    Open path For Output As #n
End If

回答by SLaks

You're looking for the InputBoxfunction.

您正在寻找该InputBox功能。

Open InputBox("Enter a file path", "Title", "default path") For Output As #n