如何从文本(.txt)文件中读取并使用VBA宏编辑器将数据放入excel 2016文档?

时间:2017-03-01 05:29:18

标签: excel vba excel-vba

我需要阅读以下文本文档(见第一张图片):Text document image

以图示的方式将数据放入Excel文档中(参见第二张图): Excel document image

我想用Excel VBA宏执行此操作,但我对如何执行此操作没有任何想法。我很擅长VBA,对于从哪里开始我没有任何想法。

3 个答案:

答案 0 :(得分:1)

使用以下子。

Sub txtImport()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Users\HARUN\Documents\Test.txt", Destination:=Range("$A$1"))
        .Name = "Test"
        .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 = True
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = True
        .TextFileColumnDataTypes = Array(1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With

答案 1 :(得分:1)

此代码将在不循环的情况下执行此操作,无论列之间的空格数是多少。

Sub Test()

 Dim Fn As String, WS As Worksheet, st As String

 Fn = "D:\tttt\test.txt" ' the file path and name
 Set WS = Sheets("Sheet1")

 'Read text file to st string
 With CreateObject("Scripting.FileSystemObject")
    If Not .FileExists(Fn) Then
        MsgBox Fn & "  : is missing."
        Exit Sub
    Else
        If FileLen(Fn) = 0 Then
            MsgBox Fn & "  : is empty"
            Exit Sub
        Else
            With .OpenTextFile(Fn, 1)
             st = .ReadAll
             .Close
            End With
        End If
    End If
 End With

 'Replace every one or more space in st string with vbTab
 With CreateObject("VBScript.RegExp")
  .Pattern = "[ ]+"
  .Global = True
  .Execute st
  st = .Replace(st, vbTab)
 End With

 'Put st string in Clipboard
 With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    .SetText st
    .PutInClipboard
 End With

 'Paste Clipboard to range
 WS.Range("A1").PasteSpecial

End Sub 

答案 2 :(得分:0)

假设您有csv文件(就像您已经显示的那样,区别在于分隔符),那么代码应该是:

Sub ReadData()
Dim line, array() As String
Set FSO = CreateObject("Scripting.FileSystemObject")
Set rfile = FSO.OpenTextFile(*your full path to the file*, 1) 'connection for reading

Dim i As Integer
i = 1
Do Until rfile.AtEndOfStream
    line = rfile.ReadLine
    array = Split(line, ",") 'I assumed that delimiter is comma
    For j = 0 To UBound(array)
        Cells(i, j + 1).Value = array(j)
    Next j 
    i = i + 1
Loop

rfile.Close

End Sub