【问题标题】:Importing data connection from text (Excel) FAST WAY从文本 (Excel) 快速导入数据连接
【发布时间】:2023-03-04 01:42:01
【问题描述】:

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

导入的数据始终采用相同的格式(在记事本中),并且值需要始终存储在相同的范围内,以便其他工作表上的公式可以工作。

谢谢

【问题讨论】:

  • 这应该是宏记录器的目标工作。将您的击键记录到宏中并为每次重复运行宏。
  • 请向我们展示您的尝试。根据网站规则,您不会从头开始获得解决方案。

标签: vba excel import excel-external-data


【解决方案1】:

根据其他人的建议,您可以通过录音轻松完成。这是一个满足您需求的示例。

 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

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

【讨论】:

  • 非常感谢。需要导入的记事本文本具有新名称。它每天都通过电子邮件发送。所以今天是E474,明天是E478。最后,我需要用户浏览文档,然后该向导在后台将其导入。在我的第一篇文章中应该感到难过,sry。
  • 添加了一个功能来为你做这件事。不要忘记接受答案。享受:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 2019-10-04
  • 2015-09-19
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多