2011-11-30 57 views
0

所以问题在于,我有一个文本文件,其中包含需要输入到程序中的所有信息(通过VBA)。但是,我需要分割一部分,然后使用分割字符串的后半部分作为我的程序。但每次运行此代码时,都会收到一个错误,指出“下标超出范围”。在文本文件中分割VBA字符串

下面的代码:

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 

请帮助。

+0

请使用工具栏上的“{}”来正确格式化代码(突出显示代码并单击按钮)。 – Fionnuala

+0

为什么用“str”加前缀变体名?要毒害下一个将维护你的代码的人的生活吗? –

+1

@iDevlop在大多数情况下,在VBA中为变量添加前缀要比在同一个名称中使用控件和变量或将保留字或函数用作变量的风险更安全。 – Fionnuala

回答

0

您的问题是在这里验证码:

Do Until strData = " " 
    Input #intFileNum, strData 
     strSplit = Split(strData, " ") 
      For Each strLine In strSplit 
       SPECS.Value = strSplit(1) 
      Next 
    Loop 

你是不是做了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 
0

另一种方法是检查拆分数组的上限。

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