简体   繁体   English

使用VBA从Yahoo Finance获取股票/公司名称

[英]Get stock/company names from Yahoo Finance using VBA

The whole code is trying to get historical data from Yahoo Finance using VBA. 整个代码都试图使用VBA从Yahoo Finance获取历史数据。 Everything works pretty fine except the code whereby I try to get the company's name using from the Yahoo site. 除了我尝试使用雅虎网站上的公司名称的代码外,其他所有东西都运行良好。

This first piece of code is just to chceck that there are no mistakes in the definition in variables or whatever. 第一部分代码只是为了证明在变量或任何其他内容的定义中没有错误。

Enum READYSTATE
READYSTATE_UNINITIALIZED = 0
READYSTATE_LOADING = 1
READYSTATE_LOADED = 2
READYSTATE_INTERACTIVE = 3
READYSTATE_COMPLETE = 4
End Enum

Sub GetData()
    Dim datasheet As Worksheet
    Dim EndDate As Date
    Dim StartDate As Date
    Dim symbol As String
    Dim qurl As String
    Dim nQuery As Name
    Dim LastRow As Integer
    Dim ohtml As HTMLText

On Error GoTo error_getdata

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.Calculation = xlCalculationManual
    Set datasheet = ActiveSheet

    StartDate = datasheet.Range("startDate").Value
    EndDate = datasheet.Range("endDate").Value
    symbol = datasheet.Range("ticker").Value
    symbol = UCase(symbol)

    'Download data from Yahoo Finance'
    Sheets("Home").Activate
    Sheets(symbol).Range("a1").CurrentRegion.ClearContents

    qurl = "http://ichart.finance.yahoo.com/table.csv?s=" & symbol
    qurl = qurl & "&a=" & Month(StartDate) - 1 & "&b=" & Day(StartDate) & _
            "&c=" & Year(StartDate) & "&d=" & Month(EndDate) - 1 & "&e=" & _
            Day(EndDate) & "&f=" & Year(EndDate) & "&g=" & Sheets(symbol).Range("a1") & "&q=q&y=0&z=" & _
            symbol & "&x=.csv"
    eurl = "https://finance.yahoo.com/quote/" & symbol & "?ltr=2"

Here is where the problem spots. 这是问题所在。 I try to scrap the html of the site looking for the company's name. 我尝试抓取该网站的html以查找公司名称。 If I look at the html code of the website, I find that the company's name is labeled as reactid="239" . 如果我查看网站的html代码,则会发现该公司的名称标记为reactid =“ 239” I guess that what I have to do is to use getelementsbyID("239") but I am not sure about that. 我想我要做的就是使用getelementsbyID(“ 239”),但是我不确定。

   '''''
Dim objIe As Object

Set objIe = CreateObject("InternetExplorer.Application")
objIe.Visible = False
objIe.navigate eurl
    Application.StatusBar = "Looking for information in Yahoo Finance"
While (objIe.Busy Or objIe.READYSTATE <> 4): DoEvents: Wend
Set xobj = objIe.querySelectorAll("[reactid=239]")
Debug.Print xobj.innerText
Set xobj = Nothing
objIe.Quit
Set objIe = Nothing
Application.StatusBar = ""

'Sort the existence of a ticker in our sheet and create a new one ' 
    Dim worksh As Integer
    Dim worksheetexists As Boolean
    Dim x As Integer
    worksh = Application.Sheets.Count
    worksheetexists = False
    For x = 1 To worksh
        If Worksheets(x).Name = symbol Then
            worksheetexists = True
            Sheets(symbol).Delete
            ActiveWorkbook.Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = symbol
            Exit For
        End If
    Next x
    If worksheetexists = False Then
        ActiveWorkbook.Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = symbol
    End If

' Load data '
QueryQuote:
    With Sheets(symbol).QueryTables.Add(Connection:="URL;" & qurl, Destination:=Sheets(symbol).Range("a1"))
      .BackgroundQuery = True
      .TablesOnlyFromHTML = False
      .Refresh BackgroundQuery:=False
      .SaveData = True
    End With

    Sheets(symbol).Range("a1").CurrentRegion.TextToColumns Destination:=Sheets(symbol).Range("a1"), DataType:=xlDelimited, _
                TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
                Semicolon:=False, Comma:=True, Space:=False, other:=False

    Sheets(symbol).Columns("A:G").ColumnWidth = 12

    'Sort data'
    LastRow = Sheets(symbol).UsedRange.Row - 2 + Sheets(symbol).UsedRange.Rows.Count

    Sheets(symbol).Sort.SortFields.Add Key:=Range("A2"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With Sheets(symbol).Sort
        .SetRange Range("A1:G" & LastRow)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
        .SortFields.Clear
    End With
Exit Sub

error_getdata:
    MsgBox ("Fatal error. Please insert a valid sticker for the stock")  
End Sub

I heed that this could not be the most efficient way to get what I want. 我注意到这可能不是获得我想要的最有效的方法。 First I want to learn how to get it done and then I will take on the efficiency of the program. 首先,我想学习如何完成它,然后才能提高程序的效率。

Edit: Using some answers, I edited a bit the code, it still shows up an error (error 438) on the line: 编辑:使用一些答案,我编辑了一些代码,它仍然在行中显示错误(错误438):

Set xobj = objIe.querySelectorAll("[reactid=239]")

I'd look into using http://www.w3schools.com/jsref/met_document_queryselectorall.asp 我会考虑使用http://www.w3schools.com/jsref/met_document_queryselectorall.asp

which can allow selection of nodes using CSS selector syntax and there is a reference for this syntax at http://www.w3schools.com/cssref/css_selectors.asp 它可以允许使用CSS选择器语法选择节点,并且http://www.w3schools.com/cssref/css_selectors.asp上有此语法的参考

So perhaps something along the lines of 所以也许是这样的

document.querySelectorAll("[reactid=239]")

Incidentally, you can browse the library if you use a Tools Reference to 顺便说一句,如果您使用工具参考来浏览库,则可以

Microsoft HTML Object Library         

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM