从Excel下拉列表中导入文本文件

时间:2018-06-14 15:09:46

标签: excel vba excel-vba

我正在尝试在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中。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

您需要修改源查询字符串,尝试:

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"""