Excel Macros for Live Stock List

Here my new post on how to use excel macros to get stocks price. You can refer screen shot below, there's table on the stock name, pricing, volume and etc. I'll explain head and tail of how to build this excel macros.
















Step to get the stock price from internet

  1. Insert a button into the excel worksheet.(Developer->Insert Button)
  2. Create excel macros name after insert the button and edit text in button.
  3. Insert title into worksheet and click the format as table. (Choose your format).
  4. The table format will look like below and insert code into macros.
  5.  Add winHttp in VBA references. (Tools > References)
  6. Insert macros code.
  7. Done. You can run you program now. If you any issue please drop me email.

Macros Code:

Sub btnRefresh_Click()
     Dim W As Worksheet: Set W = ActiveSheet

    'Find last row in worksheet
    Dim Last As Integer: Last = W.Range("A1000").End(xlUp).Row

    'Check any stock code in worksheet
    If Last = 1 Then Exit Sub

    Dim Symbols As String
    Dim i As Integer

    'Insert all the stock code into Symbols variable
    For i = 2 To Last
        Symbols = Symbols & W.Range("A" & i).Value & "+"
    Next i

    'removed last character
    Symbols = Left(Symbols, Len(Symbols) - 1)

    'get stock quotes from yahoo webpage 
    'http://finance.yahoo.com/d/quotes.csv?s=7078.KL+1015.KL+7007.KL+7054.KL&f=snl1hgkjvp
    Dim URL As String
    URL = "http://finance.yahoo.com/d/quotes.csv?s=" & Symbols & "&f=snl1hgkjvp"

    Dim Http As New WinHttpRequest
    Http.Open "GET", URL, False
    Http.Send

    'insert result to Resp variable and split it into lines
    Dim Resp As String: Resp = Http.ResponseText
    Dim Lines As Variant: Lines = Split(Resp, Chr(10))

    'split into columns
    Dim sLine As String
    For i = 0 To UBound(Lines)
        sLine = Lines(i)
        If InStr(sLine, ",") > 0 Then
            Values = Split(sLine, ",")
            W.Cells(i + 2, 2).Value = Split(Split(sLine, Chr(34) & "," & Chr(34))(1), Chr(34))(0)
            W.Cells(i + 2, 3).Value = Values(2)
            W.Cells(i + 2, 4).Value = Values(3)
            W.Cells(i + 2, 5).Value = Values(4)
            W.Cells(i + 2, 6).Value = Values(5)
            W.Cells(i + 2, 7).Value = Values(6)
            W.Cells(i + 2, 8).Value = Values(7)
            W.Cells(i + 2, 9).Value = Values(8)
        End If
    Next i
    W.Cells.Columns.AutoFit
End Sub


Comments

Popular posts from this blog

Excel VBA connect SAPRFC

How to Create Sap Gui Scripting

Simple macros to re-arrange column into upload format