Visual Basic Q&A

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries Tagged ‘amp’

How to automate Outlook by using Visual Basic

Symptoms
This article demonstrates how to programmatically control Microsoft Outlook using Automation from Visual Basic. The example demonstrates creating contacts, creating appointments, and sending messages by using Microsoft Outlook’s object-model.
Resolution
Follow the steps below to create and run the example. To run the sample, you need an early-bound reference to a Microsoft Outlook type library. The following table lists the file names of the type libraries for the different versions of Microsoft Outlook:
Collapse this tableExpand this table
Outlook versionHow type library appears in references listFilenameOutlook 97″Microsoft Outlook 8.0 Object Library”msoutl8.olbmsoutl8.olb”Microsoft Outlook 98 Object Library”msoutl85.olbOutlook 2000″Microsoft Outlook 9.0 Object Library”msoutl9.olbOutlook 2002″Microsoft Outlook 10.0 Object Library”msoutl.olbOffice Outlook 2003″Microsoft Outlook 11.0 Object Library”msoutl.olb
Building the automation sampleStart Visual Basic, and create a new Standard EXE project.From the Project menu, choose References and select Microsoft Outlook.Add a button to your form.Double-click the button, and then add the following code:

‘ Start Outlook. ‘ If it is already running, you’ll use the same instance…Dim olApp As Outlook.ApplicationSet olApp = CreateObject(“Outlook.Application”)’ Logon. Doesn’t hurt if you are already running and logged on…Dim olNs As Outlook.NameSpaceSet olNs = olApp.GetNamespace(“MAPI”)olNs.Logon ‘ Create and Open a new contact.Dim olItem As Outlook.ContactItemSet olItem = olApp.CreateItem(olContactItem) ‘ Setup Contact information…With olItem.FullName = “James Smith”.Birthday = “9/15/1975″.CompanyName = “Microsoft”.HomeTelephoneNumber = “704-555-8888″.Email1Address = “someone@microsoft.com”.JobTitle = “Developer”.HomeAddress = “111 Main St.” & vbCr & “Charlotte, NC 28226″End With’ Save Contact…olItem.Save’ Create a new appointment.Dim olAppt As Outlook.AppointmentItemSet olAppt = olApp.CreateItem(olAppointmentItem)’ Set start time for 2-minutes from now…olAppt.Start = Now() + (2# / 24# / 60#)’ Setup other appointment information…With olAppt.Duration = 60.Subject = “Meeting to discuss plans…”.Body = “Meeting with ” & olItem.FullName & ” to discuss plans.”.Location = “Home Office”.ReminderMinutesBeforeStart = 1.ReminderSet = TrueEnd With’ Save Appointment…olAppt.Save’ Send a message to your new contact.Dim olMail As Outlook.MailItemSet olMail = olApp.CreateItem(olMailItem) ‘ Fill out & send message…olMail.To = olItem.Email1AddressolMail.Subject = “About our meeting…”olMail.Body = _”Dear ” & olItem.FirstName & “, ” & vbCr & vbCr & vbTab & _”I’ll see you in 2 minutes for our meeting!” & vbCr & vbCr & _”Btw: I’ve added you to my contact list.”olMail.Send’ Clean up…MsgBox “All done…”, vbMsgBoxSetForegroundolNS.LogoffSet olNs = NothingSet olMail = NothingSet olAppt = NothingSet olItem = NothingSet olApp = Nothing Run the project, and click the button to run the code. Once the code runs, you should have a new contact named “James Smith,” an appointment scheduled in two minutes with a reminder to appear in one minute, and have sent a message to someone@microsoft.com. Also, because you added a birthday for your contact (9/15), a recurring event was added for your Outlook Calendar to remind you of the day.
New to Outlook 2002 are the two dialog boxes: one warning you that a program is trying to access e-mail addresses you have stored in Outlook and asking if you want to allow this, and another message to the effect that a program is trying to send e-mail. This feature will protect you from unknowingly being used by a virus that sends e-mail from your system.
For more information, click the following article number to view the article in the Microsoft Knowledge Base:
290500?(http://support.microsoft.com/kb/290500/) Description of the developer-related e-mail security features in Outlook 2002

How to automate Microsoft Excel from Visual Basic

Symptoms
This article demonstrates how to create and manipulate Excel by using Automation from Visual Basic.
Resolution
There are two ways to control an Automation server: by using either late binding or early binding. With late binding, methods are not bound until run-time and the Automation server is declared as Object. With early binding, your application knows at design-time the exact type of object it will be communicating with, and can declare its objects as a specific type. This sample uses early binding, which is considered better in most cases because it affords greater performance and better type safety.
To early bind to an Automation server, you need to set a reference to that server’s type library. In Visual Basic, this is done through the References dialog box found under the Project | References menu. For this sample, you will need to add a reference to the type library for Excel before you can run the code. See the steps below on how to add the reference.

Building the Automation SampleStart Visual Basic and create a new Standard EXE project. Form1 is created by default.ClickProject and then click References. The References dialog box appears. Scroll down the list until you find Microsoft Excel object library, and then select the item to add a reference to Excel. If the correct object library for your version of Excel does not appear in the list, make sure that you have your version of Excel properly installed.
NotesIf you are automating Microsoft Office Excel 2007, the type library appears as Microsoft Excel 12.0 Object Library in the References list.If you are automating Microsoft Office Excel 2003, the type library appears as Microsoft Excel 11.0 Object Library in the References list.If you are automating Microsoft Excel 2002, the type library appears as Microsoft Excel 10.0 Object Library in the References listIf you are automating Microsoft Excel 2000, the type library appears as Microsoft Excel 9.0 Object Library in the References list.If you are automating Microsoft Excel 97, the type library appears as Microsoft Excel 8.0 Object Library in the References listClick OK to close the References dialog box.Add a CommandButton to Form1.In the code window for Form1, insert the following code:

Option ExplicitPrivate Sub Command1_Click()Dim oXL As Excel.ApplicationDim oWB As Excel.WorkbookDim oSheet As Excel.WorksheetDim oRng As Excel.Range’On Error GoTo Err_Handler’ Start Excel and get Application object.Set oXL = CreateObject(“Excel.Application”)oXL.Visible = True’ Get a new workbook.Set oWB = oXL.Workbooks.AddSet oSheet = oWB.ActiveSheet’ Add table headers going cell by cell.oSheet.Cells(1, 1).Value = “First Name”oSheet.Cells(1, 2).Value = “Last Name”oSheet.Cells(1, 3).Value = “Full Name”oSheet.Cells(1, 4).Value = “Salary”‘ Format A1:D1 as bold, vertical alignment = center.With oSheet.Range(“A1″, “D1″).Font.Bold = True.VerticalAlignment = xlVAlignCenterEnd With’ Create an array to set multiple values at once.Dim saNames(5, 2) As StringsaNames(0, 0) = “John”saNames(0, 1) = “Smith”saNames(1, 0) = “Tom”saNames(1, 1) = “Brown”saNames(2, 0) = “Sue”saNames(2, 1) = “Thomas”saNames(3, 0) = “Jane”saNames(3, 1) = “Jones”saNames(4, 0) = “Adam”saNames(4, 1) = “Johnson”‘ Fill A2:B6 with an array of values (First and Last Names).oSheet.Range(“A2″, “B6″).Value = saNames’ Fill C2:C6 with a relative formula (=A2 & ” ” & B2).Set oRng = oSheet.Range(“C2″, “C6″)oRng.Formula = “=A2 & “” “” & B2″‘ Fill D2:D6 with a formula(=RAND()*100000) and apply format.Set oRng = oSheet.Range(“D2″, “D6″)oRng.Formula = “=RAND()*100000″oRng.NumberFormat = “$0.00″‘ AutoFit columns A:D.Set oRng = oSheet.Range(“A1″, “D1″)oRng.EntireColumn.AutoFit’ Manipulate a variable number of columns for Quarterly Sales Data.Call DisplayQuarterlySales(oSheet)’ Make sure Excel is visible and give the user control’ of Microsoft Excel’s lifetime.oXL.Visible = TrueoXL.UserControl = True’ Make sure you release object references.Set oRng = NothingSet oSheet = NothingSet oWB = NothingSet oXL = NothingExit SubErr_Handler:MsgBox Err.Description, vbCritical, “Error: ” & Err.NumberEnd SubPrivate Sub DisplayQuarterlySales(oWS As Excel.Worksheet)Dim oResizeRange As Excel.RangeDim oChart As Excel.ChartDim iNumQtrs As IntegerDim sMsg As StringDim iRet As Integer’ Determine how many quarters to display data for.For iNumQtrs = 4 To 2 Step -1sMsg = “Enter sales data for” & Str(iNumQtrs) & ” quarter(s)?”iRet = MsgBox(sMsg, vbYesNo Or vbQuestion _Or vbMsgBoxSetForeground, “Quarterly Sales”)If iRet = vbYes Then Exit ForNext iNumQtrssMsg = “Displaying data for” & Str(iNumQtrs) & ” quarter(s).”MsgBox sMsg, vbMsgBoxSetForeground, “Quarterly Sales”‘ Starting at E1, fill headers for the number of columns selected.Set oResizeRange = oWS.Range(“E1″, “E1″).Resize(ColumnSize:=iNumQtrs)oResizeRange.Formula = “=”"Q”" & COLUMN()-4 & CHAR(10) & “”Sales”"”‘ Change the Orientation and WrapText properties for the headers.oResizeRange.Orientation = 38oResizeRange.WrapText = True’ Fill the interior color of the headers.oResizeRange.Interior.ColorIndex = 36′ Fill the columns with a formula and apply a number format.Set oResizeRange = oWS.Range(“E2″, “E6″).Resize(ColumnSize:=iNumQtrs)oResizeRange.Formula = “=RAND()*100″oResizeRange.NumberFormat = “$0.00″‘ Apply borders to the Sales data and headers.Set oResizeRange = oWS.Range(“E1″, “E6″).Resize(ColumnSize:=iNumQtrs)oResizeRange.Borders.Weight = xlThin’ Add a Totals formula for the sales data and apply a border.Set oResizeRange = oWS.Range(“E8″, “E8″).Resize(ColumnSize:=iNumQtrs)oResizeRange.Formula = “=SUM(E2:E6)”With oResizeRange.Borders(xlEdgeBottom).LineStyle = xlDouble.Weight = xlThickEnd With’ Add a Chart for the selected dataSet oResizeRange = oWS.Range(“E2:E6″).Resize(ColumnSize:=iNumQtrs)Set oChart = oWS.Parent.Charts.AddWith oChart.ChartWizard oResizeRange, xl3DColumn, , xlColumns.SeriesCollection(1).XValues = oWS.Range(“A2″, “A6″)For iRet = 1 To iNumQtrs.SeriesCollection(iRet).Name = “=”"Q” & Str(iRet) & “”"”Next iRet.Location xlLocationAsObject, oWS.NameEnd With’ Move the chart so as not to cover your data.With oWS.Shapes(“Chart 1″).Top = oWS.Rows(10).Top.Left = oWS.Columns(2).LeftEnd With’ Free any references.Set oChart = NothingSet oResizeRange = NothingEnd Sub Press F5 to run the project.

How To Open ADO Connection and Recordset Objects

Symptoms
ActiveX Data Objects (ADO) offers several ways to open both the Connection and Recordset objects. This article presents sample code for several common techniques for each object.
Resolution
There are several ways to open a Connection Object within ADO:
By Setting the ConnectionString property to a valid Connect string and then calling the Open() method. This connection string is provider- dependent.By passing a valid Connect string to the first argument of the Open() method.By passing a valid Command object into the first argument of a Recordset’s Open method.By passing the ODBC Data source name and optionally user-id and password to the Connection Object’s Open() method. There are three ways to open a Recordset Object within ADO:
By opening the Recordset off the Connection.Execute() method.By opening the Recordset off the Command.Execute() method.By opening the Recordset object without a Connection or Command object, and passing an valid Connect string to the second argument of the Recordset.Open() method. This code assumes that Nwind.mdb is installed with Visual Basic, and is located in the C:\Program Files\DevStudio\VB directory:

Option ExplicitPrivate Sub cmdOpen_Click()Dim Conn1 As New adodb.ConnectionDim Cmd1 As New adodb.CommandDim Errs1 As ErrorsDim Rs1 As New adodb.RecordsetDim i As IntegerDim AccessConnect As String’ Error Handling VariablesDim errLoop As ErrorDim strTmp As StringAccessConnect = “Driver={Microsoft Access Driver (*.mdb)};” & _”Dbq=nwind.mdb;” & _”DefaultDir=C:\program files\devstudio\vb;” & _”Uid=Admin;Pwd=;”‘—————————’ Connection Object Methods’—————————On Error GoTo AdoError’ Full Error Handling which traverses’ Connection object’ Connection Open method #1:Open via ConnectionString PropertyConn1.ConnectionString = AccessConnectConn1.OpenConn1.CloseConn1.ConnectionString = “”‘ Connection Open method #2:Open(“[ODBC Connect String]“,”",”")Conn1.Open AccessConnectConn1.Close’ Connection Open method #3:Open(“DSN”,”Uid”,”Pwd”)Conn1.Open “Driver={Microsoft Access Driver (*.mdb)};” & _”DBQ=nwind.mdb;” & _”DefaultDir=C:\program files\devstudio\vb;” & _”Uid=Admin;Pwd=;”Conn1.Close’————————–’ Recordset Object Methods’————————–’ Don‘t assume that we have a connection object.On Error GoTo AdoErrorLite’ Recordset Open Method #1:Open via Connection.Execute(…)Conn1.Open AccessConnectSet Rs1 = Conn1.Execute(“SELECT * FROM Employees”)Rs1.CloseConn1.Close’ Recordset Open Method #2:Open via Command.Execute(…)Conn1.ConnectionString = AccessConnectConn1.OpenCmd1.ActiveConnection = Conn1Cmd1.CommandText = “SELECT * FROM Employees”Set Rs1 = Cmd1.ExecuteRs1.CloseConn1.CloseConn1.ConnectionString = “”‘ Recordset Open Method #3:Open via Command.Execute(…)Conn1.ConnectionString = AccessConnectConn1.OpenCmd1.ActiveConnection = Conn1Cmd1.CommandText = “SELECT * FROM Employees”Rs1.Open Cmd1Rs1.CloseConn1.CloseConn1.ConnectionString = “”‘ Recordset Open Method #4:Open w/o Connection & w/Connect StringRs1.Open “SELECT * FROM Employees”, AccessConnect, adOpenForwardOnlyRs1.CloseDone:Set Rs1 = NothingSet Cmd1 = NothingSet Conn1 = NothingExit SubAdoError:i = 1On Error Resume Next’ Enumerate Errors collection and display properties of’ each Error object (if Errors Collection is filled out)Set Errs1 = Conn1.ErrorsFor Each errLoop In Errs1With errLoopstrTmp = strTmp & vbCrLf & “ADO Error # ” & i & “:”strTmp = strTmp & vbCrLf & “ADO Error# ” & .NumberstrTmp = strTmp & vbCrLf & “Description” & .DescriptionstrTmp = strTmp & vbCrLf & “Source” & .Sourcei = i + 1End WithNextAdoErrorLite:’ Get VB Error Object’s informationstrTmp = strTmp & vbCrLf & “VB Error # ” & Str(Err.Number)strTmp = strTmp & vbCrLf & “Generated by ” & Err.SourcestrTmp = strTmp & vbCrLf & “Description” & Err.DescriptionMsgBox strTmp’ Clean up gracefully without risking infinite loop in error handlerOn Error GoTo 0GoTo DoneEnd Sub
ERROR NOTES Only the ADO Connection object has an errors collection. The observant reader will notice that a lightweight error handler is in effect for the RecordSet.Open examples. In the event of an error opening a RecordSet object, ADO should return the most explicit error from the OLEDB provider. Some common errors that can be encountered with the preceding code follow.
If you omit (or there is an error in) the DefaultDir parameter in the connect string, you may receive the following error:

ADO Error # -2147467259
Description [Microsoft][ODBC Microsoft Access 97 Driver] ‘(unknown)’
isn’t a valid path. Make sure that the path name is
spelled correctly and that you are connected to the server
on which the file resides.
Source Microsoft OLE DB Provider for ODBC Drivers
If there is an error in the Dbq parameter in the connect string, you may receive the following error:

ADO Error # -2147467259 Description [Microsoft][ODBC Microsoft Access 97 Driver] Couldn’t find
file ‘(unknown)’.
Source Microsoft OLE DB Provider for ODBC Drivers
The preceding errors also populate the Connection.Errors collection with the following errors:

ADO Error # -2147467259
Description [Microsoft][ODBC Driver Manager] Driver’s
SQLSetConnectAttr failed
Source Microsoft OLE DB Provider for ODBC Drivers

ADO Error # -2147467259
Description Login Failed
Source Microsoft OLE DB Provider for ODBC Drivers Note that for each error, the ADO Error number is the same, in this case translating to 0×80004005, which is the generic E_FAIL error message. The underlying Component did not have a specific error number for the condition encountered, but useful information was never-the-less raised to ADO.

Methods for transferring data to Excel from Visual Basic

Symptoms
This article discusses numerous methods for transferring data to Microsoft Excel from your Microsoft Visual Basic application. This article also presents the advantages and the disadvantages for each method so that you can choose the solution that works best for you.
Resolution
The approach most commonly used to transfer data to an Excel workbook is Automation. Automation gives you the greatest flexibility for specifying the location of your data in the workbook as well as the ability to format the workbook and make various settings at run time. With Automation, you can use several approaches for transferring your data: Transfer data cell by cellTransfer data in an array to a range of cellsTransfer data in an ADO recordset to a range of cells using the CopyFromRecordset methodCreate a QueryTable on an Excel worksheet that contains the result of a query on an ODBC or OLEDB data sourceTransfer data to the clipboard and then paste the clipboard contents into an Excel worksheet There are also methods that you can use to transfer data to Excel that do not necessarily require Automation. If you are running an application server-side, this can be a good approach for taking the bulk of processing the data away from your clients. The following methods can be used to transfer your data without Automation: Transfer your data to a tab- or comma-delimited text file that Excel can later parse into cells on a worksheetTransfer your data to a worksheet using ADOTransfer data to Excel using Dynamic Data Exchange (DDE) The following sections provide more detail on each of these solutions.
Note When you use Microsoft Office Excel 2007, you can use the new Excel 2007 Workbook (*.xlsx) file format when you save the workbooks. To do this, locate the following line of code in the following code examples:

oBook.SaveAs “C:\Book1.xls”Replace this code withwith the following line of code:

oBook.SaveAs “C:\Book1.xlsx”Additionally, the Northwind database is not included in Office 2007 by default. However, you can download the Northwind database from Microsoft Office Online.Use Automation to transfer data cell by cell With Automation, you can transfer data to a worksheet one cell at a time:

Dim oExcel As ObjectDim oBook As ObjectDim oSheet As Object’Start a new workbook in ExcelSet oExcel = CreateObject(“Excel.Application”)Set oBook = oExcel.Workbooks.Add’Add data to cells of the first worksheet in the new workbookSet oSheet = oBook.Worksheets(1)oSheet.Range(“A1″).Value = “Last Name”oSheet.Range(“B1″).Value = “First Name”oSheet.Range(“A1:B1″).Font.Bold = TrueoSheet.Range(“A2″).Value = “Doe”oSheet.Range(“B2″).Value = “John”‘Save the Workbook and Quit ExceloBook.SaveAs “C:\Book1.xls”oExcel.Quit Transferring data cell by cell can be a perfectly acceptable approach if the amount of data is small. You have the flexibility to place data anywhere in the workbook and can format the cells conditionally at run time. However, this approach is not recommended if you have a large amount of data to transfer to an Excel workbook. Each Range object that you acquire at run time results in an interface request so that transferring data in this manner can be slow. Additionally, Microsoft Windows 95 and Windows 98 have a 64K limitation on interface requests. If you reach or exceed this 64k limit on interface requests, the Automation server (Excel) might stop responding or you might receive errors indicating low memory. This limitation for Windows 95 and Windows 98 is discussed in the following Knowledge Base article:
216400?(http://support.microsoft.com/kb/216400/) Cross-process COM automation can hang client application on Win 95/98 Once more, transferring data cell by cell is acceptable only for small amounts of data. If you need to transfer large data sets to Excel, you should consider one of the solutions presented later.
For more sample code for Automating Excel, please see the following article in the Microsoft Knowledge Base:
219151?(http://support.microsoft.com/kb/219151/) How to automate Microsoft Excel from Visual BasicUse automation to transfer an array of data to a range on a worksheet An array of data can be transferred to a range of multiple cells at once:

Dim oExcel As ObjectDim oBook As ObjectDim oSheet As Object’Start a new workbook in ExcelSet oExcel = CreateObject(“Excel.Application”)Set oBook = oExcel.Workbooks.Add’Create an array with 3 columns and 100 rowsDim DataArray(1 To 100, 1 To 3) As VariantDim r As IntegerFor r = 1 To 100DataArray(r, 1) = “ORD” & Format(r, “0000″)DataArray(r, 2) = Rnd() * 1000DataArray(r, 3) = DataArray(r, 2) * 0.7Next’Add headers to the worksheet on row 1Set oSheet = oBook.Worksheets(1)oSheet.Range(“A1:C1″).Value = Array(“Order ID”, “Amount”, “Tax”)’Transfer the array to the worksheet starting at cell A2oSheet.Range(“A2″).Resize(100, 3).Value = DataArray’Save the Workbook and Quit ExceloBook.SaveAs “C:\Book1.xls”oExcel.Quit If you transfer your data using an array rather than cell by cell, you can realize an enormous performance gain with a large amount of data. Consider this line from the code above that transfers data to 300 cells in the worksheet:

oSheet.Range(“A2″).Resize(100, 3).Value = DataArray This line represents two interface requests (one for the Range object that the Range method returns and another for the Range object that the Resize method returns). On the other hand, transferring the data cell by cell would require requests for 300 interfaces to Range objects. Whenever possible, you can benefit from transferring your data in bulk and reducing the number of interface requests you make.Use automation to transfer an ADO recordset to a worksheet range Excel 2000 introduced the CopyFromRecordset method that allows you to transfer an ADO (or DAO) recordset to a range on a worksheet. The following code illustrates how you could automate Excel 2000, Excel 2002, or Office Excel 2003 and transfer the contents of the Orders table in the Northwind Sample Database using the CopyFromRecordset method.

‘Create a Recordset from all the records in the Orders tableDim sNWind As StringDim conn As New ADODB.ConnectionDim rs As ADODB.RecordsetsNWind = _”C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb”conn.Open “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & _sNWind & “;”conn.CursorLocation = adUseClientSet rs = conn.Execute(“Orders”, , adCmdTable)’Create a new workbook in ExcelDim oExcel As ObjectDim oBook As ObjectDim oSheet As ObjectSet oExcel = CreateObject(“Excel.Application”)Set oBook = oExcel.Workbooks.AddSet oSheet = oBook.Worksheets(1)’Transfer the data to ExceloSheet.Range(“A1″).CopyFromRecordset rs’Save the Workbook and Quit ExceloBook.SaveAs “C:\Book1.xls”oExcel.Quit’Close the connectionrs.Closeconn.CloseNoteIf you use the Office 2007 version of the Northwind database, you must replace the following line of code in the code example:

conn.Open “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & _ sNWind & “;” Replace this line of code with the following line of code:

conn.Open “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=” & _ sNWind & “;” Excel 97 also provides a CopyFromRecordset method but you can use it only with a DAO recordset. CopyFromRecordset with Excel 97 does not support ADO.
For more information about using ADO and the CopyFromRecordset method, please see the following article in the Microsoft Knowledge Base:
246335?(http://support.microsoft.com/kb/246335/) How to transfer data from an ADO recordset to Excel with automationUse automation to create a QueryTable on a worksheet A QueryTable object represents a table built from data returned from an external data source. While automating Microsoft Excel, you can create a QueryTable by simply providing a connection string to an OLEDB or an ODBC data source along with an SQL string. Excel assumes the responsibility for generating the recordset and inserting it into the worksheet at the location you specify. Using QueryTables offers several advantages over the CopyFromRecordset method: Excel handles the creation of the recordset and its placement into the worksheet.The query can be saved with the QueryTable so that it can be refreshed at a later time to obtain an updated recordset.When a new QueryTable is added to your worksheet, you can specify that data already existing in cells on the worksheet be shifted to accommodate the new data (see the RefreshStyle property for details). The following code demonstrates how you could automate Excel 2000, Excel 2002, or Office Excel 2003 to create a new QueryTable in an Excel worksheet using data from the Northwind Sample Database:

‘Create a new workbook in ExcelDim oExcel As ObjectDim oBook As ObjectDim oSheet As ObjectSet oExcel = CreateObject(“Excel.Application”)Set oBook = oExcel.Workbooks.AddSet oSheet = oBook.Worksheets(1)’Create the QueryTableDim sNWind As StringsNWind = _”C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb”Dim oQryTable As ObjectSet oQryTable = oSheet.QueryTables.Add( _”OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & _sNWind & “;”, oSheet.Range(“A1″), “Select * from Orders”)oQryTable.RefreshStyle = xlInsertEntireRowsoQryTable.Refresh False’Save the Workbook and Quit ExceloBook.SaveAs “C:\Book1.xls”oExcel.QuitUse the clipboard The Windows Clipboard can also be used as a mechanism for transferring data to a worksheet. To paste data into multiple cells on a worksheet, you can copy a string where columns are delimited by tab characters and rows are delimited by carriage returns. The following code illustrates how Visual Basic can use its Clipboard object to transfer data to Excel:

‘Copy a string to the clipboardDim sData As StringsData = “FirstName” & vbTab & “LastName” & vbTab & “Birthdate” & vbCr _& “Bill” & vbTab & “Brown” & vbTab & “2/5/85″ & vbCr _& “Joe” & vbTab & “Thomas” & vbTab & “1/1/91″Clipboard.ClearClipboard.SetText sData’Create a new workbook in ExcelDim oExcel As ObjectDim oBook As ObjectSet oExcel = CreateObject(“Excel.Application”)Set oBook = oExcel.Workbooks.Add’Paste the dataoBook.Worksheets(1).Range(“A1″).SelectoBook.Worksheets(1).Paste’Save the Workbook and Quit ExceloBook.SaveAs “C:\Book1.xls”oExcel.QuitCreate a delimited text file that Excel can parse into rows and columns Excel can open tab- or comma-delimited files and correctly parse the data into cells. You can take advantage of this feature when you want to transfer a large amount of data to a worksheet while using little, if any, Automation. This might be a good approach for a client-server application because the text file can be generated server-side. You can then open the text file at the client, using Automation where it is appropriate.
The following code illustrates how you can create a comma-delimited text file from an ADO recordset:

‘Create a Recordset from all the records in the Orders tableDim sNWind As StringDim conn As New ADODB.ConnectionDim rs As ADODB.RecordsetDim sData As StringsNWind = _”C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb”conn.Open “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & _sNWind & “;”conn.CursorLocation = adUseClientSet rs = conn.Execute(“Orders”, , adCmdTable)’Save the recordset as a tab-delimited filesData = rs.GetString(adClipString, , vbTab, vbCr, vbNullString)Open “C:\Test.txt” For Output As #1Print #1, sDataClose #1′Close the connectionrs.Closeconn.Close’Open the new text file in ExcelShell “C:\Program Files\Microsoft Office\Office\Excel.exe ” & _Chr(34) & “C:\Test.txt” & Chr(34), vbMaximizedFocusNoteIf you use the Office 2007 version of the Northwind database, you must replace the following line of code in the code example:

conn.Open “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & _sNWind & “;”Replace this line of code with the following line of code:

conn.Open “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=” & _sNWind & “;” If your text file has a .CSV extension, Excel opens the file without displaying the Text Import Wizard and automatically assumes that the file is comma-delimited. Similarly, if your file has a .TXT extension, Excel automatically parse the file using tab delimiters.
In the previous code sample, Excel was launched using the Shell statement and the name of the file was used as a command line argument. No Automation was used in the previous sample. However, if so desired, you could use a minimal amount of Automation to open the text file and save it in the Excel workbook format:

‘Create a new instance of ExcelDim oExcel As ObjectDim oBook As ObjectDim oSheet As ObjectSet oExcel = CreateObject(“Excel.Application”)’Open the text fileSet oBook = oExcel.Workbooks.Open(“C:\Test.txt”)’Save as Excel workbook and Quit ExceloBook.SaveAs “C:\Book1.xls”, xlWorkbookNormaloExcel.Quit For more information about using File I/O from your Visual Basic application, please see the following article in the Microsoft Knowledge Base:
172267?(http://support.microsoft.com/kb/172267/) RECEDIT.VBP demonstrates file I/O in Visual BasicTransfer data to a worksheet by using ADO Using the Microsoft Jet OLE DB Provider, you can add records to a table in an existing Excel workbook. A “table” in Excel is merely a range with a defined name. The first row of the range must contain the headers (or field names) and all subsequent rows contain the records. The following steps illustrate how you can create a workbook with an empty table named MyTable.Excel 97, Excel 2000, and Excel 2003Start a new workbook in Excel.Add the following headers to cells A1:B1 of Sheet1:
A1: FirstName B1: LastNameFormat cell B1 as right-aligned.Select A1:B1.On the Insert menu, choose Names and then select Define. Enter the name MyTable and click OK.Save the new workbook as C:\Book1.xls and quit Excel. To add records to MyTable using ADO, you can use code similar to the following:

‘Create a new connection object for Book1.xlsDim conn As New ADODB.Connectionconn.Open “Provider=Microsoft.Jet.OLEDB.4.0;” & _”Data Source=C:\Book1.xls;Extended Properties=Excel 8.0;”conn.Execute “Insert into MyTable (FirstName, LastName)” & _” values (‘Bill’, ‘Brown’)”conn.Execute “Insert into MyTable (FirstName, LastName)” & _” values (‘Joe’, ‘Thomas’)”conn.CloseExcel 2007In Excel 2007, start a new workbook.Add the following headers to cells A1:B1 of Sheet1:
A1: FirstName B1: LastNameFormat cell B1 as right-aligned.Select A1:B1.On the Ribbon, click the Formulas tab, and then click Define Name.Type the name MyTable, and then click OK.Save the new workbook as C:\Book1.xlsx, and then quit Excel. To add records to the MyTable table by using ADO, use code that resembles the following code example.

‘Create a new connection object for Book1.xlsDim conn As New ADODB.Connectionconn.Open “Provider=Microsoft.ACE.OLEDB.12.0;” & _”Data Source=C:\Book1.xlsx;Extended Properties=Excel 12.0;”conn.Execute “Insert into MyTable (FirstName, LastName)” & _” values (‘Scott’, ‘Brown’)”conn.Execute “Insert into MyTable (FirstName, LastName)” & _” values (‘Jane’, ‘Dow’)”conn.Close When you add records to the table in this manner, the formatting in the workbook is maintained. In the previous example, new fields added to column B are formatted with right alignment. Each record that is added to a row borrows the format from the row above it.
You should note that when a record is added to a cell or cells in the worksheet, it overwrites any data previously in those cells; in other words, rows in the worksheet are not “pushed down” when new records are added. You should keep this in mind when designing the layout of data on your worksheets.
Note The method to update data in an Excel worksheet by using ADO or by using DAO does not work in Visual Basic for Application environment within Access after you install Office 2003 Service Pack 2 (SP2) or after you install the update for Access 2002 that is included in Microsoft Knowledge Base article 904018. The method works well in Visual Basic for Application environment from other Office applications, such as Word, Excel, and Outlook. For more information, click the following article numbers to view the articles in the Microsoft Knowledge Base:
904953?(http://support.microsoft.com/kb/904953/) You cannot change, add, or delete data in tables that are linked to an Excel workbook in Office Access 2003 or in Access 2002
904018?(http://support.microsoft.com/kb/904018/) Description of the update for Access 2002: October 18, 2005
For additional information on using ADO to access an Excel workbook, please see the following articles in the Microsoft Knowledge Base:
195951?(http://support.microsoft.com/kb/195951/) How to query and update Excel data using ADO from ASPUse DDE to transfer data to Excel DDE is an alternative to Automation as a means for communicating with Excel and transferring data; however, with the advent of Automation and COM, DDE is no longer the preferred method for communicating with other applications and should only be used when there is no other solution available to you.
To transfer data to Excel using DDE, you can: Use the LinkPoke method to poke data to a specific range of cell(s),
-or-Use the LinkExecute method to send commands that Excel will execute. The following code example illustrates how to establish a DDE conversation with Excel so that you can poke data to cells on a worksheet and execute commands. Using this sample, for a DDE conversation to be successfully established to the LinkTopic Excel|MyBook.xls, a workbook with the name MyBook.xls must already be opened in a running instance of Excel.
Note When you use Excel 2007, you can use the new .xlsx file format to save the workbooks. Make sure that you update the file name in the following code example.
Note In this example, Text1 represents a Text Box control on a Visual Basic form:

‘Initiate a DDE communication with ExcelText1.LinkMode = 0Text1.LinkTopic = “Excel|MyBook.xls”Text1.LinkItem = “R1C1:R2C3″Text1.LinkMode = 1′Poke the text in Text1 to the R1C1:R2C3 in MyBook.xlsText1.Text = “one” & vbTab & “two” & vbTab & “three” & vbCr & _”four” & vbTab & “five” & vbTab & “six”Text1.LinkPoke’Execute commands to select cell A1 (same as R1C1) and change the font’formatText1.LinkExecute “[SELECT(""R1C1"")]“Text1.LinkExecute “[FONT.PROPERTIES(""Times New Roman"",""Bold"",10)]“‘Terminate the DDE communicationText1.LinkMode = 0 When using LinkPoke with Excel, you specify the range in row-column (R1C1) notation for the LinkItem. If you are poking data to multiple cells, you can use a string where the columns are delimited by tabs and rows are delimited by carriage returns.
When you use LinkExecute to ask Excel to carry out a command, you must give Excel the command in the syntax of the Excel Macro Language (XLM). The XLM documentation is not included with Excel versions 97 and later. For more information on how you can obtain the XLM documentation, please see the following article in the Microsoft Knowledge Base:
143466?(http://support.microsoft.com/kb/143466/) Macro97.exe file available on online services DDE is not a recommended solution for communicating with Excel. Automation provides the greatest flexibility and gives you more access to the new features that Excel has to offer.

INFO: When Is the Access AutoNumber Field Available?

Symptoms
The Access AutoNumber field is always available when a server-side cursor is used. When a client-side cursor is used, the AutoNumber field is only returned immediately when an Access 2000 database is used with OLE DB Provider for Jet 4.0 driver and with the Jet 4.0 ODBC driver.
Resolution
The following table shows when the AutoNumber field is immediately available without a requery.
Client-side cursor for Access 97 and 2000 with different drivers:

Collapse this tableExpand this table
DriverAccess 97Access 2000Office XPJet OLE DB 3.51NOUnrecognized Database FormatUnrecognized Database FormatJet OLE DB 4.0Returns 0YESYESJet ODBC 3.51NONONOJet ODBC 4.0Returns 0YESYES
The following code sample demonstrates the results shown in the above table: Open a standard EXE project in Visual Basic. Form1 is created by default.Under Project References, select Microsoft ActiveX Data Objects .Place two CommandButtons on the form.Paste the following code in the form code window:

Dim cn As ADODB.ConnectionDim rs As ADODB.RecordsetPrivate Sub Command1_Click()rs.Open “select * from ORDERS”, cn, adOpenKeyset, adLockOptimisticEnd SubPrivate Sub Command2_Click()rs.AddNewrs!CustomerID = “ALFKI”rs!EmployeeID = 1rs.UpdateBatchDebug.Print rs!OrderID & Chr(9) & rs!CustomerID & Chr(9); rs!EmployeeIDEnd SubDim sconnect As StringPrivate Sub Form_Load() Dim sconnect As StringSet cn = New ADODB.Connection Set rs = New ADODB.Recordset’Change the paths to the mdb’s in the following statements for your machine; ‘Uncomment ONE of the statements to set sconnect to a valid connection string. ‘ Using JETOLEDB drivers’Test Office 97 using JETOLEDB’sconnect = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Program Files\Microsoft Visual Studio\VB98\nwind.mdb”’sconnect = “Provider=Microsoft.Jet.OLEDB.3.51;Data Source=D:\Program Files\Microsoft Visual Studio\VB98\nwind.mdb”‘ Test Office 2000 using JETOLEDB’sconnect = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Program Files\Office2000\Office\Samples\northwind.mdb”’sconnect = “Provider=Microsoft.Jet.OLEDB.3.51;Data Source=D:\Program Files\Office2000\Office\Samples\northwind.mdb”‘Test Office XP using JETOLEDB’sconnect = “Provider=Microsoft.Jet.OLEDB.3.51;Data Source=D:\Program Files\Microsoft Office\Office10\Samples\northwind.mdb”’sconnect = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Program Files\Microsoft Office\Office10\Samples\northwind.mdb”‘ Using ODBC drivers’Test Office 97 using ODBC drivers’sconnect = “Driver={Microsoft Access Driver (*.mdb)};” & _”Dbq=nwind.mdb;” & _”DefaultDir=D:\Program Files\Microsoft Visual Studio\VB98\;” & _”Uid=Admin;Pwd=;” ”Test Office 2000 / 9 using ODBC drivers’sconnect = “Driver={Microsoft Access Driver (*.mdb)};” & _”Dbq=northwind.mdb;” & _”DefaultDir=D:\Program Files\Microsoft Office\Office\Samples;” & _”Uid=Admin;Pwd=;”‘Test Office XP / 10 using ODBC drivers’sconnect = “Driver={Microsoft Access Driver (*.mdb)};” & _”Dbq=northwind.mdb;” & _”DefaultDir=D:\Program Files\Microsoft Office\Office10\Samples;” & _”Uid=Admin;Pwd=;”cn.CursorLocation = adUseClient’cn.CursorLocation = adUseServercn.Open sconnectEnd Sub

INFO: Visual Basic Accessing an Oracle Database Using ADO

Symptoms
With Visual Basic and ADO, you have the ability to connect to anOracle database through a DSN-Less connection, execute a stored procedureusing parameters, and get return values from that stored procedure. Theexample in this article illustrates all of this functionality.
Resolution
To run the sample code in this article, you may need to download andinstall the Microsoft Data Access Components if you are using Visual Basic 5.0. The MDAC Components are located at:http://msdn.microsoft.com/en-us/data/aa937729.aspx(http://msdn.microsoft.com/en-us/data/aa937729.aspx)The following example was created against an Oracle 7.3 database through aSQL*Net 2.3 connection. All of the following code (including the storedprocedure) should work fine with Oracle 7.2. However, the Microsoft ODBCDriver for Oracle Help file states that it only supports SQL*Net 2.3.
There are two objects that need to be created on the Oracle database; atable (adooracle) and a stored procedure (adoinsert).
NOTE: If you have worked through the following Microsoft Knowledge Base article then you can use the Oracle objects created in that article (rdooracle and rdoinsert). Just change the Visual Basic code below accordingly:

167225?(http://support.microsoft.com/kb/167225/EN-US/) HOWTO: Access an Oracle Database Using RDO
Here are the data definition language (DDL) scripts to create theseobjects:
ADOORACLE – This is just a two-column table with the first column set asthe primary key:

CREATE TABLE adooracle (item_numberNUMBER(3) PRIMARY KEY,depot_numberNUMBER(3));
ADOINSERT – This procedure accepts a single numeric input parameter andreturns a single numeric output parameter. The input parameter is firstused by an input statement, then it is divided by 2 and set as the outputparameter:

CREATE OR REPLACE PROCEDURE adoinsert (insnum IN NUMBER, outnum OUT NUMBER)ISBEGININSERT INTO adooracle(Item_Number, Depot_Number)VALUES(insnum, 16);outnum := insnum/2;END;/
In SQL 3.3, use a foward slash (/) to terminate and execute the script declaring the stored procedure.
NOTE: You must use Procedures that have output parameters and not Functions when working with Oracle and ADO parameters.
The preceding scripts can be run from SQL*Plus. Once these objects have been created, you can create the Visual Basic project that will use them.
This sample project uses a simple form to send a bind parameter to theADOINSERT stored procedure and then return the output parameter from thatprocedure. Here are the steps to create the project:
Open a new project in Visual Basic and add a Reference to the Microsoft ActiveX Data Objects library.Place the following controls on the form:

ControlNameText/CaptionButtoncmdCheckCheckButtoncmdSendSendText BoxtxtInputLabellblInputInput: From the Tools menu, choose Options, Click the “Default FullModule View” option, and then click OK. This allows you to view allof the code for this project.Paste the following code into your code window:

Option ExplicitDim Cn As ADODB.ConnectionDim CPw1 As ADODB.CommandDim CPw2 As ADODB.CommandDim Rs As ADODB.RecordsetDim Conn As StringDim QSQL As StringPrivate Sub cmdCheck_Click()CPw1(0) = Val(txtInput.Text)Set Rs = CPw1.ExecuteMsgBox “Item_Number = ” & Rs(0) & “.Depot_Number = ” & Rs(1) & “.”Rs.CloseEnd SubPrivate Sub cmdSend_Click()CPw2(0) = Val(txtInput.Text)CPw2.ExecuteMsgBox “Return value from stored procedure is ” & CPw2(1) & “.”End SubPrivate Sub Form_Load()’You will need to replace the “*” with the appropriate values.Conn = “UID=*****;PWD=****;DRIVER={Microsoft ODBC for Oracle};” _& “SERVER=*****;”Set Cn = New ADODB.ConnectionWith Cn.ConnectionString = Conn.CursorLocation = adUseClient.OpenEnd WithQSQL = “Select Item_Number, Depot_Number From adooracle Where ” _& “item_number = ?”Set CPw1 = New ADODB.CommandWith CPw1.ActiveConnection = Cn.CommandText = QSQL.CommandType = adCmdText.Parameters.Append .CreateParameter(, adInteger, adParamInput)End WithQSQL = “adoinsert”Set CPw2 = New ADODB.CommandWith CPw2.ActiveConnection = Cn.CommandText = QSQL.CommandType = adCmdStoredProc.Parameters.Append .CreateParameter(, adInteger, adParamInput).Parameters.Append .CreateParameter(, adDouble, adParamOutput)End WithEnd SubPrivate Sub Form_Unload(Cancel As Integer)Cn.CloseSet Cn = NothingSet CPw1 = NothingSet CPw2 = NothingEnd Sub Run the project.When you enter a number in the text box, txtInput, and click the Send button, the Oracle stored procedure, ADOINSERT, is called. The number you entered in the text box is used as the input parameter for the procedure. The output parameter is used in a message box that is called after the stored procedure has completed processing. With your original value still in the text box, click the “Check” button. This creates a simple read-only resultset that is displayed in another message box.
What follows is a detailed explanation of the code used in thisdemonstration project.
The Form_Load event contains the code that creates the DSN-Less connection:

Conn = “UID=<uid>;PWD=<pwd>;DRIVER={Microsoft ODBC for Oracle};” _& “SERVER=<MyServer>;”Set Cn = New ADODB.ConnectionWith Cn.ConnectionString = Conn.CursorLocation = adUseClient.OpenEnd With Once you create the ADO connection object (Cn), you set several of itsparameters using the WITH statement.
The connect string that is used to open a connection to an Oracle database(or any database for that matter) is very dependant on the underlying ODBCdriver. You can see in the connect string below that the Microsoft Oracledriver you are using is named specifically by DRIVER=:

Conn = “UID=<uid>;PWD=<pwd>;DRIVER={Microsoft ODBC for Oracle};” _& “SERVER==<MyServer>;” The most important part of this connect string is the “SERVER” keyword. Thestring assigned to SERVER is the Database Alias which you set up inSQL*Net. This is the only difference in the connect string when connectingto an Oracle database. For a DSN-Less connection, as is stated in the Helpfile, you do not specify a DSN in the connect string.
Also in the Form_Load event is the code that creates the two ADO Commandobjects used in the project:

QSQL = “Select Item_Number, Depot_Number From adooracle Where ” _& “item_number = ?”Set CPw1 = New ADODB.CommandWith CPw1.ActiveConnection = Cn.CommandText = QSQL.CommandType = adCmdText.Parameters.Append .CreateParameter(, adInteger, adParamInput)End WithQSQL = “adoinsert”Set CPw2 = New ADODB.CommandWith CPw2.ActiveConnection = Cn.CommandText = QSQL.CommandType = adCmdStoredProc.Parameters.Append .CreateParameter(, adInteger, adParamInput).Parameters.Append .CreateParameter(, adDouble, adParamOutput)End With The first Command object (CPw1) is a simple parameterized query. TheCommandText has one parameter that is the item_number for the where clause.Note that the CommandType is set to adCmdText. This is different than theadCmdStoredProc CommandType in the second Command object (CPw2). The following is from the ADO Help HTML file:
“Use the CommandType property to optimize evaluation of the CommandTextproperty. If the CommandType property value equals adCmdUnknown (thedefault value), you may experience diminished performance because ADO mustmake calls to the provider to determine if the CommandText property is anSQL statement, a stored procedure, or a table name. If you know what typeof command you’re using, setting the CommandType property instructs ADO togo directly to the relevant code. If the CommandType property does notmatch the type of command in the CommandText property, an error occurs whenyou call the Execute method.”Using the WITH command, you can create and append parameters to the commandobject easily. The first parameter of the CreateParameter function is forthe name of the parameter. This has been left blank because the sampleprogram uses the index of the parameters collection to identify theindividual parameters (such as CPw1(0) to identify the first parameter).The sample program uses adInteger and adDouble datatypes. If it had used avariable length datatype, then the size parameter of the CreateParameterfunction would need to be set. Again, from the ADO Help HTML:
“If you specify a variable-length data type in the Type argument, you musteither pass a Size argument or set the Size property of the Parameterobject before appending it to the Parameters collection; otherwise, anerror occurs.”The remainder of the project is fairly straightforward and well-documentedin both the Online Help file and Books Online which come with Visual Basic.The ADO issues that are critical to working with Oracle (the connectstring and the calling of stored procedures) have been detailed in thisproject.