【问题标题】:Vba excel macro open txt file browsevba excel宏打开txt文件浏览
【发布时间】:2023-07-01 07:58:01
【问题描述】:

您好,我想打开一个 txt 文件,但它每个月都会更改,所以我需要能够选择新的文件浏览地图。

我是一个完整的 VBA 初学者,我录制了宏,但是在进入特定编码部分时,我真的不知道大多数东西。

Sub Medical_txt_excel()

With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;C:\Users\user101\Documents\Macro Sales Monthly\Dec 2016-selected\Claim Medical.txt" _
    , Destination:=Range("$A$10"))
    .Name = "Claim Medical"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False

我需要将 Claim Medical.txt 作为一个文件,我可以在使用宏时自己选择,而无需每次都更改源代码

【问题讨论】:

    标签: vba excel


    【解决方案1】:
    ChDir "C:\Users\user101\Documents\Macro Sales Monthly\Dec 2016-selected"
    Dim fpath: fPath = Application.GetOpenFilename("Text Files (*.txt),*.txt")
    if fPath = False Then Exit Sub
    With ActiveSheet.QueryTables.Add(Connection:= "TEXT;" & fPath, Destination:=Range("A10"))
      ...
    End With
    

    【讨论】:

    • 感谢这段代码完美地满足了我的需求!
    • @M.P 欢迎,很高兴为您提供帮助 :)
    【解决方案2】:

    试试这个

    Sub Medical_txt_excel()
     Dim fd As Office.FileDialog
        Set fd = Application.FileDialog(msoFileDialogFilePicker)
        fd.AllowMultiSelect = False
        fd.Title = "Please select the file."
        fd.Show
    
    With ActiveSheet.QueryTables.Add(Connection:= _
        fd.SelectedItems(1) _
        , Destination:=Range("$A$10"))
        .Name = "Claim Medical"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
    End With
    
    End Sub
    

    【讨论】: