[英]Reset For Loop Variable
我在为循环重置n = 0时遇到麻烦( For n = LBound(arrFileLines1) To UBound(arrFileLines1)
)。
示例文本文件:
7 a2 30 a1 30 a2 6 a1 5 a1 4 a1 3 a1 2 a3 1 a2
以下代码将找到第一个字符串“ 30”,并将其位置从7-255开始作为变量xxx。 第一字符串30是n = 1。
接下来,如果该行没有变量xxx
,它将进入WriteLine
。
第一遍就可以了。 我能够删除与变量xxx
相关的所有内容。
文本文件已更新为:
7 a2 30 a2 2 a3 1 a2
但是,此后n
将不会重置。 n
将开始于2。当n = 4时,我将收到错误消息:
下标超出范围:“ n”。
有什么方法可以重设n
从0开始的数字吗?
Dim arrFileLines1()
Dim xxx'
q = 0
strCheckForString = ("30")
Set objFile = objFSO.OpenTextFile("C:\Users\1234\Desktop\output.txt", 1)
Do Until objFile.AtEndOfStream
ReDim Preserve arrFileLines1(q)
arrFileLines1(q) = objFile.ReadLine
q = q + 1
Loop
objFile.Close
For n = LBound(arrFileLines1) To UBound(arrFileLines1)
If (InStr(arrFileLines1(n), strCheckForString)) Then
xxx = Mid(arrFileLines1(n), 7, 255)
Set objFile = objFSO.OpenTextFile("C:\Users\1234\Desktop\output.txt", 2)
For m = LBound(arrFileLines1) To UBound(arrFileLines1)
If ((Mid(arrFileLines1(m), 7) = xxx) = True) And (n>m) Then
objFile.WriteLine arrFileLines1(m)
Else
If ((Mid(arrFileLines1(m), 7) = xxx ) = False) Then
objFile.writeline arrFileLines1(m)
End If
End If
Next
objFile.Close
Set objFile = objFSO.OpenTextFile("C:\Users\1234\Desktop\output.txt", 1)
q = 0
Do Until objFile.AtEndOfStream
ReDim Preserve arrFileLines1(q)
arrFileLines1(q) = objFile.ReadLine
q = q + 1
Loop
objFile.Close
End If
Next
您不应该篡改For
循环的循环变量。 如果要自己控制循环变量:使用Do..Loop
代替For..Next
然后根据需要递增/递减变量。
话虽如此,对我来说,您要使用代码实现的目标还不是很清楚。 是否要删除所有以与字符串“ 30”开头的行相同的子字符串结尾的行? 是否要从样本输入中删除所有以“ a1”或“ a2”结尾的行?
如果是这样,我可能会做这样的事情:
由于无论如何都要将输入文件读入内存,因此可以这样做,并且避免了将数组追加到耗时的过程:
filename = "C:\Users\1234\Desktop\output.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
txt = fso.OpenTextFile(filename).ReadAll
lines = Split(txt, vbNewLine)
从以字符串“ 30”开头的行中建立引用列表:
Set ref = CreateObject("Scripting.Dictionary")
For Each line In lines
If Left(line, 2) = "30" Then ref(Mid(line, 7, 255)) = True
Next
然后仅将那些行写回到不包含任何这些字符串的文件中:
Set f = fso.OpenTextFile(filename, 2)
For Each line In lines
found = False
For Each s In ref.Keys
If InStr(Mid(line, 7, 255), s) > 0 Then
found = True
Exit For
End If
Next
If Not found Then f.WriteLine line
Next
f.Close
使用字典的键而不是普通数组的优点是可以自动获取唯一字符串列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.