String VBA字符串在文本文件中拆分

String VBA字符串在文本文件中拆分,string,vba,loops,split,text-files,String,Vba,Loops,Split,Text Files,问题是,我有一个文本文件,里面有我需要输入到程序中的所有信息(通过VBA)。但是,我需要拆分一个部分,然后将拆分字符串的后半部分用于我的程序。但每次运行这段代码时,都会出现一个错误,指出“下标超出范围” 代码如下: Const modelList As String = "C:\modelList.txt" Dim inFileNum As Integer Dim strData As String Dim strLine As Variant Dim strSplit As Variant

问题是,我有一个文本文件,里面有我需要输入到程序中的所有信息(通过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

请提供帮助。

您的问题在以下代码中:

    Do Until strData = " "
    Input #intFileNum, strData
        strSplit = Split(strData, " ")
            For Each strLine In strSplit
                SPECS.Value = strSplit(1)
            Next
    Loop
在运行
Split
函数之前(即,在下一个循环迭代开始时),您不会对
strData=“”
进行检查。请尝试以下操作:

    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

您的问题出现在以下代码中:

    Do Until strData = " "
    Input #intFileNum, strData
        strSplit = Split(strData, " ")
            For Each strLine In strSplit
                SPECS.Value = strSplit(1)
            Next
    Loop
在运行
Split
函数之前(即,在下一个循环迭代开始时),您不会对
strData=“”
进行检查。请尝试以下操作:

    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

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

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

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

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

请使用工具栏上的
{}
正确设置代码格式(突出显示代码并单击按钮)。为什么在变体名称前加上“str”???为了毒害下一个需要维护代码的人的生命?@iDevlop在大多数情况下,在VBA中为变量添加前缀要安全得多,而不是冒着引用同名控件和变量或使用保留字或函数作为变量的风险。请使用
{}
以正确设置代码格式(突出显示代码并单击按钮)。为什么要在变体名称前加上“str”???为了毒害下一个不得不维护代码的人的生命?@iDevlop在大多数情况下,在VBA中为变量添加前缀要安全得多,而不是冒着引用同名控件和变量或使用保留字或函数作为变量的风险。