VBA: How to read strings into a dynamic array with size to be determined (by the number of lines in the text file)
I'm having trouble finding how I can read the number of lines in a text file I'm reading without reopening the file again. Thanks in advance for your time. I apologize in advance if you manage to find what I'm talking about easily (which I have done my due diligence already).
Sub CreateMessage()
Dim filepath As String
' Read filepath in spreadsheet
开发者_如何学Pythonfilepath = Cells(6, 8)
' Parse string contents from script
' Open file
Open filepath For Input As #1
How do I read each line of the text file into a dynamic array, with size to be determined by the number of lines in the text file right at this line?
' Close file
Close #1
End Sub
If you're reading them into an array, you can just keep the current maximum size of the array in a variable and use ReDim
(redimension) to expand it when you need more space. ReDim
changes the size of an array on the fly and you probably want to make sure you do it in steps rather than one at a time.
Something like (unchecked, so you'll need to verify):
option explicit
option base 0
dim numlines as integer
dim maxlines as integer
numlines = 0
maxlines = 0
dim lines() as string
for every line in file ' not actually valid syntax '
if numlines = maxlines then
maxlines = maxlines + 100
redim preserve lines (maxlines)
end if
lines(numlines) = line
numlines = numlines + 1
end for
redim preserve lines (numlines)
And that for
loop is not actually valid syntax, but it has no bearing on the method used for for redimensioning. You should replace it with whatever code you're getting your information from the file.
You could read in the entire file and then use
arr = Split(contents, vbcrlf)
To get the array. Assuming it has the typical windows line delimiter.
精彩评论