【问题标题】:Unable to extract Text using VBA, when there are multiple Classname , tagname and attributes with same name无法使用 VBA 提取文本,当有多个具有相同名称的 Classname 、 tagname 和属性时
【发布时间】:2019-08-19 19:38:27
【问题描述】:

我正在尝试从 IE 浏览器中提取“span”类下的内部文本,但遇到了问题。下面是HTML代码

第一个 html sn-p

<div class="SectionStart" style="display: block;" oraload="oraDisplayNone(item,'newDev','Y','=')" oraInitDisplayStyle="block">
  <label oramdlabel="CM_SN">Serial Number</label>
<!--style tag has been added-->
  <span class="oraDefault" style="left: -5px; top: 4.5px; position: relative;" orafield="MSerialNumber" oraType="string;precision:20" oraErrorElement="mSerialNumber">G4A001</span>
</div>

第二个 html sn-p

<div class="SectionStart">
  <label oramdlabel="CM_SN">Serial Number:</label>
<!--style tag has been added-->
  <span class="oraDefault" style="left: -5px; top: 4.5px; position: relative;" orafield="MSerialNumber" oraType="string;precision:20" oraErrorElement="mSerialNumber">E5W807</span>

</div>

这里的问题是按照下面的代码,在尝试获取第二个值“E5W807”时,我只获取了不需要的值“G4A001”。

请指导我如何解决仅提取文本“E5W807”的问题。

 Set objSubCollec = objCollection(0).contentWindow.document.getElementById("Page")
    Set objElement = objSubCollec.contentWindow.document.getElementById("Frame_4")
    objElement.Focus
   Set objElement1 = objElement.contentWindow.document
   Set elm2 = objElement1.getElementsByTagName("span")

          For Each e1 In elm2
              If e1.getAttribute("orafield") = "MSerialNumber" Then
                 temp = e1.innerText
                'MsgBox temp
                Worksheets("Sheet1").Range("B6") = temp
        Exit For
    End If
    Next

【问题讨论】:

  • 当它找到满足您条件的span 元素时,您将指示代码退出For Each/Next 循环。所以它没有机会遍历剩余的元素。如果您删除 Exit For,它将循环遍历每个 span 元素。
  • 完整文档中必须有多个"MSerialNumber"。所以你需要循环打印那些。正如@Domenic 所说,您将在找到第一个实例后退出循环。
  • 不是一个答案,而是一个忠告...用于您的 VBA 的缩进相当不一致;你会惊讶于正确的缩进对阅读代码和发现错误有多大的影响。

标签: excel vba


【解决方案1】:

不妨试试这个:

它将从B6开始依次打印所有找到的数字。

Set objSubCollec = objCollection(0).contentWindow.document.getElementById("Page")
Set objElement = objSubCollec.contentWindow.document.getElementById("Frame_4")
objElement.Focus
Set objElement1 = objElement.contentWindow.document
Set elm2 = objElement1.getElementsByTagName("span")


i = 6
For Each e1 In elm2
    If e1.getAttribute("orafield") = "MSerialNumber" Then
       temp = e1.innerText
       Worksheets("Sheet1").Range("B & i") = temp
       i = i + 1
    End If
Next

【讨论】:

  • 感谢您的提示。我现在可以提取所需的相应文本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多