2011-11-30 2 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 

당신은 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 
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