打开并读取文本文件,然后使用分隔符复制文件的内容

时间:2017-11-07 14:29:51

标签: excel vba excel-vba

我在excel VBA中有一个代码,它打开并读取一个文本文件,然后它复制文件的内容,但它不会粘贴分隔符。

我想复制我打开并阅读的文件的内容,然后将文件的内容粘贴到另一个工作簿。

以下是我目前的代码

Sub ImportTextFile()

Dim SheetName As String
Dim TMPWorkBook As Workbook
Dim FilePath As String
Dim TxtFilePath As String
Dim TxtFileName As String

Set WB = ThisWorkbook

path = "C:\Users\"

SheetName = "Test_Result"
TxtFileName = path & "244.txt"

Workbooks.OpenText Filename:= _
    TxtFileName _
    , Origin:=437


Set TMPWorkBook = ActiveWorkbook
TMPWorkBook.Sheets(1).Select
Cells.Select
Selection.Copy

'ResultWB.Activate
Windows("Sample.xlsb").Activate

'ResultWB.Sheets(SheetName).Select
Sheets("Data").Select
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Cells.Select
Cells.EntireColumn.AutoFit
ActiveSheet.Range("A1").Select
TMPWorkBook.Close savechanges:=False

Image of result

enter image description here

1 个答案:

答案 0 :(得分:0)

而不是开放&复制/粘贴内容我建议您导入分隔数据,就像通过菜单选项" Data => From Text"一样。 根据您发布的示例,您可能会成功使用Space作为分隔符。 以下是一些可以帮助您入门的代码:

Dim wb As Workbook, sh As Worksheet
Dim path As String
Dim qt As QueryTable

path = "M:\SSC TQM\Projects\_CC\BPLG\ETAPAI_20170724.txt"
Set wb = Workbooks("TEMPLATE BPLG.xlsb")
Set sh = wb.Worksheets("Data")

'Clear existing Query Tables

For Each qt In sh.QueryTables
    qt.Delete
Next qt


With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;" & path, Destination:=Range( _
    "$A$1"))
    .Name = "Data"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 850
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = True
    .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)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
sh.QueryTables(1).Delete