I'm trying to scrape some Yahoo Finance data from their website, and I've inherited some VBA which allows me to do this mostly.
However, as you can see from the picture, I have a problem where the script tries to scrape a field that is blank. If it's blank, I want to put an "N/A" return in the field, rather than just putting the 'next' field in it's place.
Would anyone be able to help me to fix this?
Thanks in advance!
However, as you can see from the picture, I have a problem where the script tries to scrape a field that is blank. If it's blank, I want to put an "N/A" return in the field, rather than just putting the 'next' field in it's place.
VBA Code:
Sub qTest_3()
Call clear_data
Dim myrng As Range
Dim lastrow As Long
Dim row_count As Long
Dim ws As Worksheet
Set ws = Sheets("Main")
col_count = 2
row_count = 2
'Find last row
With ws
lastrow = .Range("A" & .Rows.Count).End(xlUp).Row
End With
'set ticker range
Set myrng = ws.Range(Cells(2, 1), Cells(lastrow, 1))
'llop through tickers
For Each ticker In myrng
'Send web request
Dim URL2 As String: URL2 = "https://finance.yahoo.com/quote/" & ticker & "/key-statistics?p=" & ticker
Dim Http2 As New WinHttpRequest
Http2.Open "GET", URL2, False
Http2.Send
Dim s As String
'Get source code of site
s = Http2.ResponseText
Dim metrics As Variant
'**** Metric fields here
metrics = Array("dividendRate", "dividendYield", "fiveYearAvgDividendYield", "trailingAnnualDividendRate", "exDividendDate")
'Split string here
For Each element In metrics
firstTerm = Chr(34) & element & Chr(34) & ":{" & Chr(34) & "raw" & Chr(34) & ":"
secondTerm = "," & Chr(34) & "fmt" & Chr(34)
nextPosition = 1
On Error GoTo err_hdl
Do Until nextPosition = 0
startPos = InStr(nextPosition, s, firstTerm, vbTextCompare)
stopPos = InStr(startPos, s, secondTerm, vbTextCompare)
split_string = Mid$(s, startPos + Len(firstTerm), stopPos - startPos - Len(secondTerm))
nextPosition = InStr(stopPos, s, firstTerm, vbTextCompare)
Exit Do
Loop
On Error GoTo 0
Dim arr() As String
arr = Split(split_string, ",")
metric = arr(0)
'Output to sheet
ws.Range(Cells(row_count, col_count), Cells(row_count, col_count)).Value = metric
col_count = col_count + 1
getData:
Next element
Dim symbol As String
symbol = ticker
col_count = 2
row_count = row_count + 1
Next ticker
MsgBox ("Done")
Exit Sub
err_hdl:
ws.Range(Cells(row_count, col_count), Cells(row_count, col_count)).Value = "N/A"
Resume getData
End Sub
Sub clear_data()
Dim ws As Worksheet
Set ws = Sheets("Main")
Dim lastrow, lastcol As Long
Dim myrng As Range
With ws
lastrow = .Range("A" & .Rows.Count).End(xlUp).Row
End With
lastcol = ws.Cells(1, Columns.Count).End(xlToLeft).Column
Set myrng = ws.Range(Cells(2, 2), Cells(lastrow, lastcol))
myrng.Clear
End Sub
Would anyone be able to help me to fix this?
Thanks in advance!