【问题标题】:VBA string split in Text File在文本文件中拆分 VBA 字符串
【发布时间】:2011-11-30 15:08:01
【问题描述】:

所以问题来了,我有一个文本文件,其中包含我需要输入到我的程序中的所有信息(通过 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

请帮忙。

【问题讨论】:

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

标签: string vba loops split text-files


【解决方案1】:

您的问题在此代码中:

    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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多