Change hardcoded file path to user prompted in VBA?

北战南征 提交于 2019-12-30 07:17:48

问题


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.

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.


回答1:


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



回答2:


You're looking for the InputBox function.

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


来源:https://stackoverflow.com/questions/7152660/change-hardcoded-file-path-to-user-prompted-in-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!