文本文件中的 VBA 字符串拆分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8328064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA string split in Text File
提问by user1073626
So here's the problem, I have a text file with all the information I need to input into my program (through VBA). But, there's one section I need to split, then use the second half of the split string for my program. BUT every time I run this code, I get an error stating the "subscript is out of range".
所以这就是问题所在,我有一个文本文件,其中包含需要输入到我的程序中的所有信息(通过 VBA)。但是,我需要拆分一个部分,然后将拆分字符串的后半部分用于我的程序。但是每次运行此代码时,都会收到一条错误消息,指出“下标超出范围”。
Here's the code:
这是代码:
Const modelList As String = "C:\modelList.txt"
Dim inFileNum As Integer
Dim strData As String
Dim strLine As Variant
Dim strSplit As Variant
Dim intCount As Integer
intFileNum = FreeFile
intCount = 0
Open modelList For Input As #intFileNum
Do Until EOF(intFileNum)
Input #intFileNum, strData
Do Until strData = "[SPECS]"
Input #intFileNum, strData
Do Until strData = " "
Input #intFileNum, strData
strSplit = Split(strData, " ")
For Each strLine In strSplit
SPECS.Value = strSplit(1)
Next
Loop
Loop
Loop
Close #intFileNum
Please help.
请帮忙。
回答by mwolfe02
Your problem is in this code here:
您的问题出在此代码中:
Do Until strData = " "
Input #intFileNum, strData
strSplit = Split(strData, " ")
For Each strLine In strSplit
SPECS.Value = strSplit(1)
Next
Loop
You are not doing the check for strData = " "
until after the Split
function is run (ie, at the start of the next loop iteration). Try the following instead:
strData = " "
直到Split
函数运行之后(即在下一次循环迭代开始时),您才进行检查。请尝试以下操作:
Do
Input #intFileNum, strData
If strData = " " Or InStr(strData, " ") = 0 Then Exit Do
strSplit = Split(strData, " ")
For Each strLine In strSplit
SPECS.Value = strSplit(1)
Next
Loop
回答by teddy2
Another approach would be checking for the upper bound of the split array.
另一种方法是检查拆分数组的上限。
strSplit = Split(strData, " ")
For Each strLine In strSplit
'~~~Assuming that you always want the second element, if available
If (UBound(strSplit)) > 0 Then
SPECS.Value = strSplit(1)
Else
SPECS.Value = strSplit(0)
End If
Next