Search

Talking to the outside world in Excel 2003

0 views

Preparing Your Development Environment

When you first hear about writing C# code that runs inside an Excel 2003 workbook, the idea of blending the flexibility of .NET with the familiarity of spreadsheets can be a bit intimidating. The good news is that the setup process is straightforward if you follow the steps below.

First, you’ll need the Office 2003 beta kit. The kit contains the necessary type libraries and development files that let Visual Studio recognize the Excel object model. You can download the kit from Microsoft’s official preview site: Office 2003 Beta Kit. Once the download completes, run the installer and follow the prompts to add the Office 2003 components to your Visual Studio 2003 installation.

Next, install the Office add‑on for Visual Studio .NET 2003. This add‑on provides project templates, design‑time support, and debugging tools specifically for Office development. The installer is available at Microsoft Download Center. After installing, restart Visual Studio so that the new templates become visible.

Open Visual Studio and create a new “Microsoft Office 2003 Excel Add‑in” project. The template sets up the project structure, adds references to Microsoft.Office.Interop.Excel, and creates a default workbook. The project file will look something like this: ExcelAddIn1. Visual Studio generates a skeleton ThisWorkbook class that you’ll use to hook into workbook events.

To test the environment, add a simple message box to the Workbook_Open event:

Prompt
Private Sub Workbook_Open()</p> <p> MsgBox "Hello from C#!", vbInformation</p> <p>End Sub</p>

Save the workbook, close Excel, and reopen the file. You should see the message box appear automatically when the workbook loads. If it does, your development environment is ready for the next step.

At this point, it’s a good idea to take a screenshot of the workbook to document the initial state. The screenshot below shows an empty sheet with a simple message box that confirms the add‑in runs properly. In the final version of the article, the screenshot will be replaced with the populated workbook after the data retrieval code executes.

When you’re ready, download the sample code that demonstrates how to fetch stock quotes from the NASDAQ website and populate the spreadsheet. The ZIP file is available at Get the code here. Unzip the archive and open the project solution inside Visual Studio. The code is divided into two main parts: the data retrieval logic (the GetQuote method) and the workbook event that calls this method when the file opens.

Before you dive into the code, keep in mind that Excel 2003’s VBA environment could also call external web services, but it would require complex Windows API calls and string manipulation. By using C#, you avoid many of those complications and can write cleaner, more maintainable code.

In the next section, we’ll explore how the GetQuote function works, how it parses raw HTML from NASDAQ, and why this approach remains viable even though the website layout may change over time.

Fetching Real‑Time Stock Quotes

The heart of the sample lies in the GetQuote method, a lightweight routine that scrapes the NASDAQ website for the latest price of a given ticker symbol. NASDAQ does not provide a public API that returns XML or JSON, so the method resorts to classic web scraping. This approach is simple and effective as long as the structure of the page remains stable.

The method begins by building a URL that points to the stock’s quote page. The base URL is http://www.nasdaq.com/symbol/ and the ticker symbol is appended in lowercase. For example, to fetch information for Apple Inc. (AAPL), the URL becomes http://www.nasdaq.com/symbol/aapl. The method then sends an HTTP GET request using the WebRequest.Create method:

Prompt
Dim request As WebRequest = WebRequest.Create(url)</p> <p>Dim response As WebResponse = request.GetResponse()</p>

Once the response is received, the code extracts the response stream and reads the entire body into a string. The stream is interpreted as ASCII, which matches the encoding used by NASDAQ’s pages:

Prompt
Using reader As New StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII)</p> <p> html = reader.ReadToEnd()</p> <p>End Using</p>

At this point, html contains the raw HTML of the page. The next step is to locate the numeric value that represents the current price. The method searches for a known marker in the source code that precedes the price. For NASDAQ, the marker appears as <td class="quotePrice">. Once the marker’s index is found, the method slices the string to extract the number that follows:

Prompt
Dim startIndex As Integer = html.IndexOf("<tdquotePrice"">")</p> <p>If startIndex = -1 Then Return String.Empty</p> <p>startIndex += 23 ' length of the marker</p> <p>Dim endIndex As Integer = html.IndexOf("<", startIndex)</p> <p>Dim price As String = html.Substring(startIndex, endIndex - startIndex)</p>

Because the HTML is unstructured, the method must trim whitespace and handle any stray HTML entities. The final price string is returned to the caller, which can then place it into a worksheet cell.

It might seem fragile to rely on raw HTML parsing, but in practice, the overall layout of NASDAQ’s quote pages changes infrequently. Even when a redesign occurs, the price cell typically remains within the same table structure, so a small adjustment to the marker string usually restores functionality. The author of the sample updated the code after a recent redesign by modifying the marker to <spanquote_price"">. The ability to tweak a single line of code keeps the system robust against minor website changes.

For those who prefer a more structured data source, alternative services like Yahoo Finance or Alpha Vantage offer free APIs that return JSON. However, those services may impose request limits or require API keys. The web‑scraping approach presented here bypasses those constraints and keeps the example lightweight.

The GetQuote method also includes basic error handling. If the HTTP request fails or the price marker isn’t found, the method returns an empty string. The workbook event that calls GetQuote checks for this condition and leaves the cell blank rather than throwing an exception that would crash Excel.

In the next section we’ll see how to integrate this method into the workbook’s lifecycle, automatically update cells when the file opens, and create a chart that reacts to the new data.

Populating Excel and Building a Dynamic Chart

With the environment ready and the quote‑retrieval logic in place, the final step is to connect the two pieces so that a user sees live data as soon as the workbook opens. In the sample, the Workbook_Open event loops through a predefined list of ticker symbols, fetches each price, and writes the result to column B of the active sheet.

Dim symbols As Variant

symbols = Array("AAPL", "MSFT", "GOOG", "IBM", "ORCL")

Dim i As Integer

For i = 0 To UBound(symbols)

Dim price As String

price = GetQuote(symbols(i))

Cells(i + 1, 2).Value = price

Next i

End Sub

The list of symbols can be edited directly in the code or, for a more flexible solution, pulled from a configuration sheet or a database. Once the cells are populated, the chart on the sheet refreshes automatically because Excel recalculates whenever the underlying data changes. In the screenshot that accompanies the article, you’ll notice a line chart that updates to display the most recent price points as soon as the workbook loads.

Because the workbook reads data only at opening time, it doesn’t constantly poll the web. If you need to refresh data on a schedule, you can add a timer or a button that triggers the same loop. For example, a simple Refresh Data button could call a public method that re‑runs the quote retrieval logic and repopulates the sheet.

Beyond stock prices, the same pattern can be adapted to pull weather data, sports scores, or any publicly available information that is accessible via HTTP. The key is to isolate the web request into a reusable method, then call that method from the workbook event that fits your use case. Because the logic lives in C#, you can reuse it across multiple Excel projects, reducing duplication and easing maintenance.

When working with external data, it’s good practice to cache the response or handle throttling to avoid hammering a public website. The sample includes a simple Thread.Sleep(500) between requests to introduce a half‑second delay. Adjust this value as needed for the data source you target.

Finally, after testing the workbook with real data, you can package the add‑in for distribution. The Visual Studio project produces a .xla file that you can load into any Excel 2003 instance by going to Tools → Add‑Ins → Browse and selecting the file. Once loaded, the workbook will automatically fetch and display fresh quotes every time it opens, giving users a powerful, data‑driven spreadsheet without leaving Excel.

Suggest a Correction

Found an error or have a suggestion? Let us know and we'll review it.

Share this article

Comments (0)

Please sign in to leave a comment.

No comments yet. Be the first to comment!

Related Articles