1

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".

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.

3
  • Please use {} on the toolbar to format code correctly (highlight the code and click the button). Commented Nov 30, 2011 at 15:31
  • Why do you prefix a variant name with "str" ??? To poison the life of the next guy who will have to maintain your code ? Commented Nov 13, 2012 at 8:03
  • 1
    @iDevlop For the most part, it is much safer to prefix variables in VBA rather than risk ending up referring to both a control and a variable with the same name or using a reserved word or function as a variable. Commented Nov 15, 2012 at 12:42

2 Answers 2

1

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:

    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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.