Pulling Upside/downside Capture Ratio from morning

2019-01-28 12:53发布

问题:

First Time Long Time.

New to this VBA thing, however catching on.

I'm interested in pulling the upside/downside capture ratio for a lot of mutual funds and want to automate the process. The table I am taking the info from is not your typical table; I guess it's a "dynamic object" on morningstar's website Here is the website.

http://performance.morningstar.com/fund/ratings-risk.action?t=FDSAX&region=USA&culture=en-us

This is specically for SunAmerica's Focus Dividend Fund; however I want to do it for many funds Here is what I have for the code right now; I got it to msgbox, but don't know how to loop and get the information on excel.

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column=Range("upDown").Row And _
  Target.Column= Range("upDown").Column Then

  Dim IE as New InternetExplorer
  IE.Visible=False
  IE.navigate "http://performance.morningstar.com/fund/ratings-risk.action?t=" _
     & Range("upDown").Value

  Do
    DoEvents
  Loop Until IE.readyState = READYSTATE_Complete
    Dim Doc as HTMLDocument
    Set Doc = IE.document
    Dim sTR As String 'got the "TR" from google chrome inspect element
    sTR = Trim(Doc.getElementsByTagName("tr")(45).innerText)

This is where I am stuck. I know that I need to used the 'split' in order to line item each of the data I need. Example 1year upside 1 year downside 3 year upside 3 year downside.

So once I get it on excel, I need to have excel run through all of my tickers...about 1500 to pull that data since it updates once per month.

Thank you in advance...you'll be a life-saver...literally I might shoot myself if I don't figure it out :)

回答1:

Try below code.

Sub Test()

    Dim IE As Object, Doc As Object, lastRow As Long, tblTR As Object, tblTD As Object, strCode As String
    lastRow = Range("A65000").End(xlUp).Row


    Set IE = CreateObject("internetexplorer.application")
    IE.Visible = True


    For i = 1 To lastRow

        strCode = "FDSAX"    ' Range("A" & i).value  ' kindly change it as per your requirement. Currently hardcoded

        IE.navigate "http://performance.morningstar.com/fund/ratings-risk.action?t=" & "FDSAX"

        Do While IE.readystate <> 4: DoEvents: Loop

        Set Doc = CreateObject("htmlfile")
        Set Doc = IE.document

tryAgain:
        Set tblTR = Doc.getelementbyid("div_upDownsidecapture").getelementsbytagname("tr")(3)

        If tblTR Is Nothing Then GoTo tryAgain

        j = 2
        For Each tblTD In tblTR.getelementsbytagname("td")
            tdVal = Split(tblTD.innerText, vbCrLf)
            Cells(i, j) = tdVal(0)
            Cells(i, j + 1) = tdVal(1)
            j = j + 2
        Next


    Next
End Sub