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

我需要阅读以下文本文件(见第一张图片): 文本文档图像

并以图片的方式将数据放入Excel文档中(请参阅第二张图): Excel文档图像

我想用Excel VBAmacros做这个,但是我没有丝毫的想法。 我对VBA非常了解,从哪里开始我都没有丝毫的想法。

使用下面的子。

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 

这段代码将不会循环,也不pipe列之间有多less空格。

 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 

假设你有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 ji = i + 1 Loop rfile.Close End Sub