有时我发现自己面临填充数组的问题,而不必先对其进行维度。大多数情况下,我可以通过循环验证条件已经验证了多少次,ReDim
我的数组相应,然后用相同的循环用数据填充数组。
这是(特别是对于大阵列)非常耗时且没有优化。
今天我发现自己以编程方式“读取”了一个文本文件,其中我必须验证一条线在空线之前重复多少次,而不知道有多少线可能存在。我只知道这些行的最小数量是1。
该文件如下所示:
TITLE Very_Much_Potato
INFO lol?
FREQUENCY 123456.7
DEF_DIAG 1 Potato1.TXT
DEF_DIAG 2 Potato2.TXT
ELEMENT 1 0.00 0.00 -300.00 0.250 0.0 6.0 1 2 0.00 0.0 0.0
ELEMENT 2 0.00 0.00 -200.00 0.500 20.0 6.0 1 2 0.00 0.0 0.0
ELEMENT 3 0.00 0.00 -100.00 0.750 40.0 6.0 1 2 0.00 0.0 0.0
ELEMENT 4 0.00 0.00 0.00 1.000 60.0 6.0 1 2 0.00 0.0 0.0
ELEMENT 5 0.00 0.00 100.00 0.750 80.0 6.0 1 2 0.00 0.0 0.0
ELEMENT 6 0.00 0.00 200.00 0.500 100.0 6.0 1 2 0.00 0.0 0.0
ELEMENT 7 0.00 0.00 300.00 0.250 120.0 6.0 1 2 0.00 0.0 0.0
END
我使用以下代码“阅读”:
Dim i As Integer
Dim fd As FileDialog, FilePath As String
Dim fst As Object, StringData As String
Dim Name As String, Frequency As Double, DefDiag() As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Title = "Select the file you would like to import"
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Potato File", "*.pot"
.FilterIndex = 1
If .Show <> -1 Then
End
End If
FilePath = .SelectedItems(1)
End With
Set fst = CreateObject("ADODB.Stream")
fst.Charset = "utf-8"
fst.lineseparator = 10 ' sets enter as end-of-line separator
fst.Open
fst.LoadFromFile FilePath
StringData = fst.ReadText(-2) ' -2 to read until lineseparator
Name = Mid(StringData, 7)
StringData = fst.ReadText(-2)
StringData = fst.ReadText(-2)
Frequency = CDbl(Mid(StringData, 11))
Do Until fst.ReadText(-2) = ""
StringData = fst.ReadText(-2) ' DEF_DIAG
DefDiag(i) = Right(StringData, Len(StringData) - InStrRev(StringData, " "))
i = i + 1
Loop
当然,它会在DefDiag
数组开始填充的地方停止。关于如何不对其进行维度的任何想法?
答案 0 :(得分:1)
我愿意;
将整个文件加载到内存中,解析为行数组
Open FilePath For Input As #1
DefDiag = Split(Input$(LOF(1), #1), ChrW$(10))
Close #1
分配与DefDiag
循环DefDiag
进行处理,在需要存储值时添加到第二个数组的下一个索引
当您完成Redim
第二个数组以截断其空尾
答案 1 :(得分:1)
我不认为在VBA中填充没有维度的数组是可能的,但您可以在循环时使用ReDim Preserve
来重新排列数组:
...
i=1
Do Until fst.ReadText(-2) = ""
StringData = fst.ReadText(-2) ' DEF_DIAG
ReDim Preserve DefDiag(i)
DefDiag(i) = Right(StringData, Len(StringData) - InStrRev(StringData, " "))
i = i + 1
Loop