What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleRetrieve stock prices from the Web
Keywordsstock, quotes, prices, Web, Inet control, Internet Transfer control, download
CategoriesControls, Utilities
Testing this type of program can be difficult if you don't have a permanent Internet connection. This program works around this by providing a mode where it loads data from a text file instead of from the Web. If the USE_TEST_FILE constants is defiend as True, the program reads data from a text file. Otherwise it uses the Internet Transfer control (Inet) to send a query to a Yahoo stock server and reads the results.

The following code builds a query string similar to the following, which fetches stock quotes for DIS, COKE, amd MCI:


It uses the Inet control's OpenURL method to open the URL and read the result. The result is text similar to the following:


Notice that this isn't HTML so it will probably confuse your browser. The program, however, has no trouble displaying the resulting text.

' Set the following constant to True to load
' from a test data file instead of from
' the Web.
'Private Const USE_TEST_FILE = True
Private Const USE_TEST_FILE = False

Private Function LoadTestFile() As String
Dim fname As String
Dim fnum As Integer

    fname = App.Path & "\quote.htm"
    fnum = FreeFile
    Open fname For Input As fnum
    LoadTestFile = Input$(LOF(fnum), #fnum)
    Close fnum
End Function

Private Sub cmdGetQuotes_Click()
Dim not_first_symbol As Boolean
Dim symbol As String
Dim query_url As String
Dim i As Integer
Dim response As Variant

    MousePointer = vbHourglass
    txtQuotes.Text = ""
    ' Prepare a URL to get the quotes.
        response = LoadTestFile
        query_url = _
        For i = txtSymbol.LBound To txtSymbol.UBound
            symbol = LCase$(Trim$(txtSymbol(i).Text))
            If Len(symbol) > 0 Then
                If not_first_symbol Then _
                    query_url = query_url & ","
                query_url = query_url & symbol
                not_first_symbol = True
            End If
        Next i

        ' Open the URL.
        response = inetQuotes.OpenURL(query_url)
    End If

    ' Display the response.
    txtQuotes.Text = response

    MousePointer = vbDefault
End Sub

' Cancel any pending commands.
Private Sub Form_Unload(Cancel As Integer)
End Sub
Note that the data is separated by commas (that's what the "csv" means in the URL - Comma Separated Values) so you could use Split to easily separate the values and process them further.

For another example, see Retrieve stock prices from the Web, example.

Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.