[英]Unable to let a macro append results to the already existing results every time I run it
I've created a macro using xmlhttp requests to fetch some tabular content from a webpage.我创建了一个宏,使用 xmlhttp 请求从网页中获取一些表格内容。 The macro is doing fine.
宏做得很好。 What I wish to do now is let the macro append the result to the already existing results every time I run it.
我现在想做的是让宏 append 每次运行时都将结果转换为已经存在的结果。
To be clearer, when I run the macro, I find it writing results in sheet1
upto row 61 no matter how many times i run it.更清楚地说,当我运行宏时,我发现它在
sheet1
中写入结果,直到第 61 行,无论我运行它多少次。 However, what i wish to do is when I rerun the macro, it will write results after row 61 excluding the header and then again after row 121 and so on.但是,我希望做的是当我重新运行宏时,它将在第 61 行之后写入结果,不包括 header,然后在第 121 行之后再次写入,依此类推。
I've tried with:我试过:
Sub GetTabularContent()
Const Url = "https://sofifa.com/players?offset=0"
Dim Html As New HTMLDocument, S$, R&, C&
Dim wb As Workbook, ws As Worksheet
Dim elem As Object, tRow As Object
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")
With New ServerXMLHTTP
.Open "GET", Url, False
.send
S = .responseText
End With
With New HTMLDocument
.body.innerHTML = S
For Each elem In .getElementsByTagName("table")(0).Rows
For Each tRow In elem.Cells
C = C + 1: ws.Cells(R + 1, C) = tRow.innerText
Next tRow
C = 0: R = R + 1
Next elem
End With
End Sub
This is exactly how the result is being written.这正是结果的编写方式。
How can I let the macro append results to the already existing results if there is any?如果有的话,我怎样才能让宏 append 结果变为已经存在的结果?
The best way is to get the last row of Excel and write after it.最好的办法是拿到Excel的最后一行,然后写。 This function will do it :
这个 function 可以做到:
Public Function LastRow(wsName As String, Optional columnToCheck As Long = 1) As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(wsName)
LastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row
End Function
To call the function, try this:要调用 function,请尝试以下操作:
dim myLastRow as Long
myLastRow = LastRow(ws.Name)
C = myLastRow
For Each elem In .getElementsByTagName("table")(0).Rows
For Each tRow In elem.Cells
C = C + 1: ws.Cells(R + 1, C) = tRow.innerText
Next tRow
C = myLastRow : R = R + 1
Next elem
Give it a few tries, if it does not work exactly as you want it to be, I have not tested it.试一试,如果它不能完全按照你想要的那样工作,我还没有测试过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.