2017-02-07 73 views
2

嗨,我想打開一個txt文件,但它每個月都在變化,所以我需要能夠選擇新的一個瀏覽地圖。VBA excel宏開放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 

我需要索賠Medical.txt是一個文件,我可以用宏不用每次都改變源代碼時選擇自己

回答

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 
+1

謝謝這段代碼適合我想要的東西! –

+0

@ M.P歡迎,很高興幫助:) –

0

試試這個

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