首页 > 解决方案 > 通过 vba 读取 html 文件

问题描述

在我的项目中,我正在读取一个带有 vba 代码的 html 文件,并使用一些子字符串对其进行扫描,然后我正在使用这些子字符串创建一个 json 文件。SUBTASK是我的子字符串之一。当我扫描 html 文件时,它找到了 9 个SUBTASK,但在我的 html 文件中有超过 9 个。我的代码是这样的。

            For i = 1 To lastrow                    
                txt = Cells(i, 1)                    
                If txt = "All" Or txt = "ALL" Or txt = "V2500-A5" Then   'Or txt = "V2500-A1"
                    engType = txt
                End If

                If txt = "About" Then GoTo skipNextRow

                If Left(txt, 1) <> "0" And Left(txt, 5) <> "TASK " And Left(txt, 4) <> "DMC:" And Right(Left(txt, 11), 8) <> "SUBTASK " Then GoTo skipNextRow                                                            

                If Left(txt, 5) = "TASK " Then
                    locationTASK = InStr(1, txt, "TASK ")

                ElseIf Left(txt, 4) = "DMC:" Then
                    locationDMC = InStr(1, txt, "DMC:")
                    locationIssueNo = InStr(1, txt, "Issue No:")
                    locationIssueDate = InStr(1, txt, "Issue Date:")

                ElseIf Right(Left(txt, 11), 8) = "SUBTASK " Then

                    Debug.Print "Subtask: " & txt
                    locationSUBTASK = InStr(1, txt, "SUBTASK ")

                End If                    

skipNextRow:

           Next i

           ReDim Preserve arrApplicability(w): arrApplicability(w) = engType
           ReDim Preserve arrPartNo(w): arrPartNo(w) = myTemp
           w = w + 1

我在SUBTASK部分的问题,在其他部分没有问题。

标签: vba

解决方案


您查找文本的方式有点不稳定。预期格式的变化空间不大。在没有看到您的实际输入的情况下,这将是很多猜测,但它就是这样。
我怀疑 subtask 这个词被放置在不同的列中,而您只会得到从第 4 列开始的那些。这里有一些提示可能会使您的调试更容易。

  1. 这将帮助您找到丢失的行以及它们的位置。替换End If
    Else
        locationSUBTASK = InStr(1, txt, "SUBTASK")
        Debug.Print "SUBTASK found in position " & locationSUBTASK 
    End If
  1. Mid是一个可以帮助你一点的功能。替换Right(Left(txt, 11), 8)Mid(txt, 4, 8)。对您当前的问题并没有真正的帮助,但仍然如此。
  2. 了解正则表达式。这是一个可以帮助您入门的代码段:
    Dim RegExp As Object
    Dim Matches As Object

    Dim txt As String
    txt = "something SUBTASK yada yada"

    Set RegExp = CreateObject("VBScript.RegExp")

    RegExp.Pattern = ".*SUBTASK (.*)"
    Set Matches = RegExp.Execute(txt)
    Debug.Print Matches(0).SubMatches(0)

该模式的".*SUBTASK (.*)"意思是“在一行中的任何位置找到单词'SUBTASK'并跟踪它后面的内容。”。该(.*)零件将被识别为子匹配。


推荐阅读