我试图将下拉值写入excel,但是我遇到了一些困难。
Heres是HTML代码:
<div class="select__box" id="wrapBox">
<div class="option" name="US" data-id="United States">
<div class="option__icon"><span class="flag-icon flag-icon-3x flag-icon-us flag-icon-squared option__flag"></span></div>
<div class="option__title">United States</div>
</div>
<div class="option" name="CA" data-id="Canada">
<div class="option__icon"><span class="flag-icon flag-icon-3x flag-icon-ca flag-icon-squared option__flag"></span></div>
<div class="option__title">Canada</div>
</div>
<div class="option" name="GB" data-id="United Kingdom">
<div class="option__icon"><span class="flag-icon flag-icon-3x flag-icon-gb flag-icon-squared option__flag"></span></div>
<div class="option__title">United Kingdom</div>
</div>
<div class="option" name="DO" data-id="Dominican Republic">
<div class="option__icon"><span class="flag-icon flag-icon-3x flag-icon-do flag-icon-squared option__flag"></span></div>
<div class="option__title">Dominican Republic</div>
</div>
<div class="option" name="CN" data-id="China">
<div class="option__icon"><span class="flag-icon flag-icon-3x flag-icon-cn flag-icon-squared option__flag"></span></div>
<div class="option__title">China</div>
</div>
</div>
首先,我需要获取国家/地区名称,我可以使用代码执行此操作
x = objIE.document.getElementsByClassName("option").Length
nextEmptyRow = 1
For i = 0 To x - 1
cnt = objIE.document.getElementsByClassName("option")(i).innerText
ActiveWorkbook.Sheets("Sheet1").Range("A" & nextEmptyRow).Value = cnt
nextEmptyRow = nextEmptyRow + 1
Next i
然后我想获得国家/地区代码(美国,加州,GB,DO,CN)
我正在尝试使用类似的代码,但它给了我一个错误,而且我无法找出可能存在的问题。
For i = 0 To x - 1
cnt2 = objIE.document.getElementByClassName("option")(i).getAttribute("name").innerText
ActiveWorkbook.Sheets("Sheet1").Range("B" & nextEmptyRow2).Value = cnt2
nextEmptyRow2 = nextEmptyRow2 + 1
Next i
答案 0 :(得分:0)
解析字符串是一个选项吗?
这里我将HTML存储在Activesheet的单元格A1中以进行测试:
Option Explicit
Sub test()
Dim parseString As String
parseString = ActiveSheet.Range("A1")
Dim codesArray() As String
codesArray = Split(parseString, "name=""")
Dim i As Long
For i = 1 To UBound(codesArray)
Debug.Print Left$(codesArray(i), InStr(1, codesArray(i), " ") - 2)
Next i
End Sub
表格中的HTML(用于测试)
答案 1 :(得分:0)
感谢您的建议,QHarr,但我找到了一个更简单的解决方案。
显然我需要更具体地指出HTML代码中的行,我遗漏了getElementById("wrapBox")
,.innerText
或.Value
是不必要的。
For i = 0 To x - 1
cnt = objIE.document.getElementsByClassName("option")(i).innerText
ActiveWorkbook.Sheets("Sheet1").Range("A" & nextEmptyRow).Value = cnt
cnt2 = objIE.document.getElementById("wrapBox").getElementsByClassName("option")(i).getAttribute("name")
ActiveWorkbook.Sheets("Sheet1").Range("B" & nextEmptyRow).Value = cnt2
nextEmptyRow = nextEmptyRow + 1
Next i