从文本导入数据连接(Excel)快速方式

时间:2017-11-07 08:13:07

标签: excel vba excel-vba import excel-external-data

是否有更快的方法将数据从文本导入Excel工作表,然后单击并定义参数。有些用户不知道如何使用导入向导。有没有可能通过Macros做到这一点?

导入的数据始终采用相同的格式(在记事本中),并且值必须始终存储在相同的范围内,以便另一张表中的公式可以正常工作。

由于

1 个答案:

答案 0 :(得分:0)

正如其他人所建议的那样,您可以轻松地进行录制。这是一个满足您需求的样本。

 Dim src_file_name As String
 src_file_name = openDialog
    ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(1)).Name = "temp_text"
    With ThisWorkbook.Worksheets("temp_text").QueryTables.Add(Connection:= _
        "TEXT;" & src_file_name _
        , Destination:=ThisWorkbook.Worksheets("temp_text").Range("$A$1"))
        .Name = "text_to_excel"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 65001
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With

正如您所提到的,您要让用户选择文本文件。只需包含以下方法 -

Function openDialog() As String
Dim fd As Office.FileDialog

Set fd = Application.FileDialog(msoFileDialogFilePicker)

With fd

  .AllowMultiSelect = False

  ' Set the title of the dialog box.
  .Title = "Please select the file."

  ' Clear out the current filters, and add our own.
  .Filters.Clear
  .Filters.Add "Text Files", "*.txt"
  .Filters.Add "All Files", "*.*"

  ' Show the dialog box. If the .Show method returns True, the
  ' user picked at least one file. If the .Show method returns
  ' False, the user clicked Cancel.
  If .Show = True Then
    openDialog = .SelectedItems(1)

  End If
End With
End Function

(注意 - 不要忘记像我一样在上面调用此函数。)