我想知道是否有人知道在Excel VBA中解析相当大的数据文件的方法,因为无论何时我尝试简单数据解析它都会崩溃程序。数据格式如此
593972,Data,15:59:59.820,9519,9519,Px(25.5),9519,9500,10001,10226,10451,0,0,0,0,0,28.7604,25.4800,25.4841
并且大约有300万行格式完全相同,如果第一个值(在上面的情况为593972)是特定数字,我想在行中提取某些值。我对VBA很新,所以任何帮助都会非常感激。非常感谢您的时间!
答案 0 :(得分:1)
尝试使用FSO;修改以满足您的需求。
Sub ParseFile()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim strLine As String
Dim arrLine() As String
Dim objFile
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set objFile = fso.OpenTextFile("C:\Temp\Text File.txt", ForReading) '<modify path as needed
Do Until objFile.AtEndOfStream
strLine = Trim(objFile.Readline)
If (strLine <> "") Then
arrLine = Split(strLine, ",") 'one dimensional array
'parse the arrLine to test for the data you need
Dim FirstValue as String
FirstValue = arrLine(0)
If FirstValue = "593972" Then
'put the data in Excel if desired/needed
End If
End If
Loop
objFile.Close
Set objFile = Nothing
End Sub
答案 1 :(得分:0)
下面的Sub
打开一个文本流,逐行读取,并验证第一个字段是否对每一行都有一定的值;让它适应你想做的事情:
Public Sub ReadAndValidate( _
ByVal FileName As String, _
ByVal FieldKey As String _
)
' This function doesn't do error handling, assumes that the '
' field separator is "," and that the key field is first. '
' It uses the "Scripting" lib; "Microsoft Scripting Runtime"'
' needs to be referenced by the containing workbook. '
Dim line As String
Dim keylen As Long
Dim fs As Scripting.FileSystemObject
Dim f As Scripting.TextStream
Let FieldKey = FieldKey & "," ' add the separator to the key '
Let keylen = Strings.Len(FieldKey)
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile( _
FileName:=FileName, _
IOMode:=IOMode.ForReading _
)
While Not f.AtEndOfStream
Let line = f.ReadLine()
If Strings.Left$(line, keylen) = FieldKey Then
' replace the statement below with your code '
Debug.Print line
End If
Wend
f.Close
End Sub