我正在尝试提取" href"链接根据表格中可用的值将网页链接到我的Excel工作表。我为一个值做同样的事情是成功的,但我无法循环。
下面是一个运行良好的值的代码:
Dim X As String
X = ActiveCell.Value ' I have selected the cell "A1" before even starting the macro
Set ElementCol = IE.document.getElementsByTagName("a")
For Each link In ElementCol
If link.innerHTML = Jesus Then
ActiveCell.Offset(0, 1).Value = link.href ' I will have the value in the "B1"
End If
Next
这是截图
现在,当我尝试循环代码运行时,它在所有单元格中给出了相同的值 这是我试过的代码:
Dim intRowCount As Integer
Dim i As Integer
Dim X As String
X = ActiveCell.Value
intRowCount = Range("A1").CurrentRegion.Rows.Count
For i = 1 To intRowCount
Set ElementCol = IE.document.getElementsByTagName("a")
For Each link In ElementCol
If link.innerHTML = X Then
ActiveCell.Offset(0, 1).Value = link.href
ActiveCell.Offset(1, 0).Select
End If
Next
Next i
这是截图
我希望我以一种可以理解的方式解释情况,请原谅我的任何错误。图中的链接也是样本!!!
以下是重新设计的代码:
X = Range("A1").CurrentRegion.Rows.Count
For i = 1 To X
ActiveCell.Offset(1, 0).Select
Dim Y As String
Jesus = ActiveCell.Value
Set ElementCol = IE.document.getElementsByTagName("a")
For Each link In ElementCol
If link.innerHTML = Y Then
ActiveCell.Offset(0, 1).Value = link.href
End If
Next
Next i
答案 0 :(得分:3)
You should avoid using ActiveCell
, instead simply reference the cells in full. You've also created a loop with i
but not referred to this.
The main issue is that you are setting the value of X
outside of the loop and then comparing the link to this value which will remain the same for every iteration.
Try the following:
Dim eRow As Long
Dim i As Long
Dim ws as Worksheet
Set ws = Thisworkbook.Sheets("SheetName")
eRow = ws.Cells(ws.Rows.count, 1).End(xlUp).Row
Set ElementCol = IE.document.getElementsByTagName("a")
For i = 1 To eRow
For Each link In ElementCol
If link.innerHTML = ws.Cells(i, 1).Value Then
ws.Cells(i, 2).Value = link.href
End If
Next
Next i