【问题标题】:Importing .txt into Excel with VBA not adding a column使用VBA将.txt导入Excel而不添加列
【发布时间】:2018-06-26 02:20:28
【问题描述】:

我有此代码可将 .txt 文件导入我的 Excel 工作表 (Sheet1)。在Sheet1 中,我有一个公式的第一列,所以我将我的文本数据导入到 B1 中。 这段代码第一次做得很好,但是下面的代码在右边添加了一列,将选定的单元格移动到 A 列的公式中。数据仍然复制到 B1 中,但不知何故先添加了一列。有什么帮助吗?

Sheets("Sheet1").Select
Columns("B:F").Select
Selection.ClearContents

Dim Ret

Ret = Application.GetOpenFilename("Text Files (*.txt), *.txt", Title:="Select text file(.txt)")

If Ret <> False Then
    With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;" & Ret, Destination:=Range("$B$1"))
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = True
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 2)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
    End With

End If

【问题讨论】:

    标签: excel vba text import


    【解决方案1】:

    改变 .RefreshStyle = xlInsertDeleteCells.RefreshStyle = xlOverWriteCells,然后只运行一次宏。之后,您可以通过点击数据选项卡上的刷新数据按钮来简单地让 Excel 完成工作并摆脱宏。 见:http://jkp-ads.com/articles/importtext.asp

    【讨论】:

    • 太完美了,非常感谢!我在哪里可以阅读有关所有这些详细信息的更多信息?
    • 在我上面已经提到的文章中我猜?还是您在寻找其他信息?
    • 是的,我读过。我的意思是,例如,如果我想导入一个以空格分隔的 .txt 文件,我该如何更改相同的代码?或任何其他更改...妈妈谢谢
    • 关键是您实际上不需要任何VBA代码,只需使用文章中描述的Excel用户界面即可。
    猜你喜欢
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 2018-01-08
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多