[英]Import text file from drop-down in Excel
我正在嘗試在Excel中創建一個宏,該宏基於工作表上單元格中的值導入文本文件。 一個單元格指定目錄的路徑,第二個帶有下拉菜單的單元格包含文件名,包括擴展名。
我試圖記錄一個宏,在該宏中我從有問題的目錄中導入了一個文件,但是我很難更改它,以便它使用路徑和文件名而不是常量值的兩個單元格。
原始記錄的宏如下所示:
Sub txt_import()
' txt_import Macro
ActiveWorkbook.Queries.Add Name:="testfile", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Csv.Document(File.Contents(""D:\testpath\testfile.txt""),[Delimiter="";"", Columns=10, Encoding=1252, QuoteStyle=QuoteStyle.None])," & Chr(13) & "" & Chr(10) & " #""Change Type"" = Table.TransformColumnTypes(Source,{{""Column1"", type text}, {""Column2"", type text}, {""Column3"", type text}, {""Colu" & _
"mn4"", type text}, {""Column5"", type text}, {""Column6"", type text}, {""Column7"", type text}, {""Column8"", type text}, {""Column9"", type text}, {""Column10"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Change Type"""
ActiveWorkbook.Worksheets.Add
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=testfile;Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [testfile]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "_testfile"
.Refresh BackgroundQuery:=False
End With
End Sub
目錄路徑位於Sheet1 A1上,帶有文件名的下拉列表位於Sheet3 A2中。
任何幫助是極大的贊賞!
您需要修改Source查詢字符串,嘗試:
Sub txt_import()
' txt_import Macro
Dim path as String, filename as String, fullFileName as String
path = ThisWorkbook.Worksheets("Sheet1").Range("A1").Value
filename = ThisWorkbook.Worksheets("Sheet3").Range("A2").Value
fullFileName = path & Application.PathSeparator & filename
ActiveWorkbook.Queries.Add Name:="testfile", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Csv.Document(File.Contents(" & fullFileName & "),[Delimiter="";"", Columns=10, Encoding=1252, QuoteStyle=QuoteStyle.None])," & Chr(13) & "" & Chr(10) & " #""Change Type"" = Table.TransformColumnTypes(Source,{{""Column1"", type text}, {""Column2"", type text}, {""Column3"", type text}, {""Colu" & _
"mn4"", type text}, {""Column5"", type text}, {""Column6"", type text}, {""Column7"", type text}, {""Column8"", type text}, {""Column9"", type text}, {""Column10"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Change Type"""
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.