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 ‘microsoft data access’

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.

INFO: Programmer’s Guide to Using ADO in Visual Basic

Symptoms
This article presents useful information for anyone wanting to takeadvantage of the ActiveX Data Objects (ADO) within Visual Basic versions5.0 and 6.0. Topics covered are:
How to find ADO Knowledge Base ArticlesADO Resources/Points of Information

Resolution
How to Find ADO Knowledge Base ArticlesADO is not a technology that ships with one particular product, and has been treated as a product in its own right.
For more information about this issue, please see the following article in the Microsoft Knowledge Base:
183606?(http://support.microsoft.com/kb/183606/EN-US/)ActiveX Data Objects (ADO) Frequently Asked Questionsand choose “ActiveX Data Objects” as the product and enter your specific search topic.
You can also pick “All Microsoft Products” or use the MSDN or other non-Web-based Knowledge Base search mechanisms, and search for the keyword “kbado,” which all ADO articles contain.
ADO Resources/Points of InformationADO originally shipped with the OLE-DB Software Development Kit (SDK), but now is part of Microsoft Data Access Components or MDAC. To learn more about it, please visit the Microsoft Universal Data Access Web site:
http://msdn.microsoft.com/en-us/data/aa937729.aspx(http://msdn.microsoft.com/en-us/data/aa937729.aspx)or the ADO-specific Web page at:
http://msdn.microsoft.com/en-us/library/ms811450.aspx(http://msdn.microsoft.com/en-us/library/ms811450.aspx)

INFO: Deploy database applications with the Package and Deployment Wizard (PDW)

Symptoms
The Microsoft Data Object Libraries may be referenced in your Visual Basic project. When the Package and Deployment Wizard (PDW) is used to build the installation, the PDW scans the project files and determines which dependency files need to be distributed.
This article provides the general information you need to distribute any of the following Data Object Libraries with your Visual Basic project: Microsoft Data Access Objects (DAO) 3.51 Object LibraryMicrosoft Data Access Objects (DAO) 3.6 Object LibraryMicrosoft Remote Data Object (RDO) 2.0Microsoft ActiveX Data Objects (ADO) 2.0, 2.1, 2.5, or 2.6 Library
Resolution
The files are listed in the Setup’s file that is created by the PDW for distribution.
For additional information on how each section in the Setup.lst file is used, click the following article number to view the article in the Microsoft Knowledge Base:
189743?(http://support.microsoft.com/kb/189743/) Description of Setup.lst sections The following sections describe points to be aware of when you distribute any of the Data Object Libraries.
Microsoft Data Access Objects (DAO) 3.51 Object LibraryIntrinsic data control incompatibility with Microsoft Access 2000 (Jet 4.0) If you use the intrinsic data control in your project and you attempt to connect to a Microsoft Access 2000 database, you may receive the following error message:

Unrecognized Database Format This error message occurs because the DAO generic data control is based on Jet 3.51 and does not recognize Jet 4.0 database formats. Access 2000 is a Jet 4.0 format database. Prior to Microsoft Visual Studio 6.0 Service Pack 4 (SP4), the workaround for this problem was to open a recordset with DAO code, and then assign it to the recordset property of a data control. For additional information, click the following article number to view the article in the Microsoft Knowledge Base:
238401?(http://support.microsoft.com/kb/238401/) PRB: Unrecognized database format error message when upgrading to Access 2000 This problem does not exist with the data control that ships with Microsoft Visual Studio 6.0 Service Pack 6.
Visual Studio 6.0 Service Pack 6 can be obtained at the Visual Studio 6.0 Service Pack Web site:
http://msdn2.microsoft.com/en-us/vstudio/aa718364.aspx(http://msdn2.microsoft.com/en-us/vstudio/aa718364.aspx)Jet 3.51 OLE DB Provider is not included in MDAC 2.1 or later The Jet OLE DB Provider requires the version number of the provider in order to connect to an Access database. If your application specifies Version 3.51 of the Jet OLE DB provider in a connection string or a UDL, and you install ADO by redistributing MDAC 2.1, you are likely to receive the following error message:

3706: ADO could not find the specified provider This error message occurs because MDAC 2.0 installs version 3.51 of the Jet OLE DB provider while MDAC 2.1 installs version 4.0 of the Jet OLE DB Provider, but does not install version 3.51. For additional information, click the following article number to view the article in the Microsoft Knowledge Base:
197902?(http://support.microsoft.com/kb/197902/) PRB: Jet 3.51 OLE DB Provider is not installed with MDAC 2.1 or later
Microsoft Data Access Objects (DAO) 3.6 Object Library DAO version 3.6 is required for applications that use DAO to read and write to Access 2000 databases. If Access 2000 (or DAO 3.6) is already installed on the destination computer, then no additional steps are required. If it is not, it is necessary to distribute DAO 3.6. However, there is currently no redistributable for DAO 3.6. In order to redistribute DAO 3.6, it is necessary to install DCOM, redistribute MDAC 2.1(GA) or later, and ensure that the DAO DLL is also distributed and registered on the destination computer.
For additional information, click the following article number to view the article in the Microsoft Knowledge Base:
233002?(http://support.microsoft.com/kb/233002/) How to redistribute DAO 3.6
Microsoft Remote Data Object (RDO) 2.0 In order for RDO to be properly distributed and installed, ODBC must already be installed on the destination computer. ODBC can be installed through the odbcst32.exe file, which is located in the ODBC Folder under the SQL/i386 directory on Visual Basic 6.0 Disk 2. ODBC can also be installed by including the MDAC redistributable in the distribution that is outlined in the “References” section covering distributing ADO/MDAC. To determine all of the files needed to distribute for RDO to work successfully on a computer that does not have Visual Basic installed, you can generate a dependency (.dep) file with the Package and Deployment Wizard. To generate a dependency file that shows the files needed for RDO when running the PDW, complete the following steps: Create a Standard EXE project in Visual Basic. Form1 is created by default.Add a reference to Microsoft Remote Data Object 2.0.Save this project and run the Package and Deployment Wizard on it.Select the Package option.On the Package Type, choose Dependency File, and then proceed through the wizard to completion. When you are finished, you have a file with a .dep extension that can be opened with Microsoft Notepad. MSRDO20.dll and its dependencies are shown in this file.
You want to ensure that these files are included with the distribution. If these files are not listed on the Included Files dialog box when you run the Package and Deployment Wizard, include them by clicking Add in the dialog box.
Microsoft ActiveX Data Objects (ADO) 2.0, 2.1 or 2.5 Library The PDW does not distribute mdac_typ unless there is a specific reference to an ADO Library (any version) in the project.
You can also add mdac_typ.exe manually by clicking Add in the Included Files dialog box when you run the Package and Deployment Wizard. The wizard uses the MDAC_Typ.exe file in the …\Wizards\PDWizard\Redist folder. Obtain the MDAC Components at the following Microsoft Web site:
http://msdn2.microsoft.com/en-us/data/aa937695.aspx(http://msdn2.microsoft.com/en-us/data/aa937695.aspx) For additional information how the PDW distributes MDAC, click the following article number to view the article in the Microsoft Knowledge Base:
217754?(http://support.microsoft.com/kb/217754/) How to control which MDAC version the Package and Deployment Wizard (PDW) distributes The installation of Microsoft Data Access Components (MDAC) requires that DCOM be already installed on the destination computer: For Windows 95 computers, install DCOM95.For Windows 98 computers, install DCOM98.Download the latest version of DCOM from the following Microsoft Web page:
http://www.microsoft.com/downloads/details.aspx?familyid=08B1AC1B-7A11-43E8-B59D-0867F9BDDA66&displaylang=en(http://www.microsoft.com/downloads/details.aspx?familyid=08B1AC1B-7A11-43E8-B59D-0867F9BDDA66&displaylang=en) If DCOM is not already installed on the destination computer, you may receive one of the following error messages:

Unable to load file ‘msdadc.dll’ to register it
-or-

DLL registration failed For additional information, click the following article number to view the article in the Microsoft Knowledge Base:
191704?(http://support.microsoft.com/kb/191704/) PRB: Unable to load file to register it during setup

How To Use Data Links to Create a Connection String at Run Time

Symptoms
This article demonstrates how to programmatically use Data Links feature of the Microsoft Data Access Components in order to generate a connection string at run-time.
Resolution
In version 2.0 of the Microsoft Data Access Components, Data Links were introduced. Data Link files are similar to ODBC DSN files, but allow you to select an OLE DB provider to connect to your database. With the OLE DB Provider for ODBC drivers, you can also connect to an ODBC data source.
Double-clicking on a Data Link file displays a set of property pages that allow you to build a connection string to connect to your database.
You can use this same functionality in your Visual Basic applications by following the steps listed below: Launch Visual Basic and open a new Standard Exe project. Form1 is created by default.Select References from the Project menu, and then select Microsoft OLE DB Service Component 1.0 Type Library from the list of available references.Add a CommandButton to your form.Add the following code to the Click event of your CommandButton:

Private Sub Command1_Click()Dim objDataLink As New DataLinksDim strConn As StringstrConn = objDataLink.PromptNewMsgBox “The connection string you created is:” & _vbCrLf & strConnEnd Sub Run the project. When you click the CommandButton, you will see the Data Links property pages. Once you have specified how you want to connect to your database and click the OK button, you’ll see the connection string in a dialog box.

How To Use ADO with Excel Data from Visual Basic or VBA

Symptoms
This article discusses the use of ActiveX Data Objects (ADO) with Microsoft Excel spreadsheets as a data source. The article also highlights syntax issues and limitations specific to Excel. This article does not discuss OLAP or PivotTable technologies or other specialized uses of Excel data.
For additional information, click the article number below to view the article in the Microsoft Knowledge Base:
303814?(http://support.microsoft.com/kb/303814/EN-US/) How To Use ADOX with Excel Data from Visual Basic or VBA
Resolution
INTRODUCTION The rows and columns of a Microsoft Excel spreadsheet closely resemble the rows and columns of a database table. As long as users keep in mind that Microsoft Excel is not a relational database management system, and recognize the limitations that this fact imposes, it often makes sense to take advantage of Excel and its tools to store and analyze data.
Microsoft ActiveX Data Objects makes it possible to treat an Excel workbook as if it were a database. This article discusses how to accomplish this in the following sections: Connect to Excel with ADORetrieve and Edit Excel Data with ADORetrieve Data Source Structure (Metadata) from ExcelNOTE: The testing for this article was conducted with Microsoft Data Access Components (MDAC) 2.5 on Microsoft Windows 2000 with Visual Basic 6.0 Service Pack 3 and Excel 2000. This article may not acknowledge or discuss differences in behavior that users may observe with different versions of MDAC, Microsoft Windows, Visual Basic, or Excel.
Connect to Excel with ADO ADO can connect to an Excel data file with either one of two OLE DB Providers included in MDAC: Microsoft Jet OLE DB Provider -or-
Microsoft OLE DB Provider for ODBC DriversHow to Use the Microsoft Jet OLE DB Provider The Jet Provider requires only two pieces of information in order to connect to an Excel data source: the path, including the file name, and the Excel file version.
Jet Provider Using a Connection String

Dim cn as ADODB.ConnectionSet cn = New ADODB.ConnectionWith cn .Provider = “Microsoft.Jet.OLEDB.4.0″ .ConnectionString = “Data Source=C:\MyFolder\MyWorkbook.xls;” & _”Extended Properties=Excel 8.0;” .OpenEnd With Provider Version: It is necessary to use the Jet 4.0 Provider; the Jet 3.51 Provider does not support the Jet ISAM drivers. If you specify the Jet 3.51 Provider, at run time you receive the following error message:

Couldn’t find installable ISAM. Excel Version: Specify Excel 5.0 for an Excel 95 workbook (version 7.0 of Excel), and Excel 8.0 for an Excel 97, Excel 2000, or Excel 2002 (XP) workbook (versions 8.0, 9.0, and 10.0 of Excel).
Jet Provider Using the Data Link Properties Dialog Box
If you use the ADO Data Control or the Data Environment in your application, then the Data Link Properties dialog box is displayed to gather the necessary connection settings.
On the Provider tab, select the Jet 4.0 Provider; the Jet 3.51 Provider does not support the Jet ISAM drivers. If you specify the Jet 3.51 Provider, at run time you receive the following error message:

Couldn’t find installable ISAM. On the Connection tab, browse to your workbook file. Ignore the “User ID” and “Password” entries, because these do not apply to an Excel connection. (You cannot open a password-protected Excel file as a data source. There is more information on this topic later in this article.)On the All tab, select Extended Properties in the list, and then click Edit Value. Enter Excel 8.0; separating it from any other existing entries with a semicolon (;). If you omit this step, you receive an error message when you test your connection, because the Jet Provider expects a Microsoft Access database unless you specify otherwise.Return to the Connection tab and click Test Connection. Note that a message box appears informing you that the process has succeeded. Other Jet Provider Connection Settings
Column headings: By default, it is assumed that the first row of your Excel data source contains columns headings that can be used as field names. If this is not the case, you must turn this setting off, or your first row of data “disappears” to be used as field names. This is done by adding the optional HDR= setting to the Extended Properties of the connection string. The default, which does not need to be specified, is HDR=Yes. If you do not have column headings, you need to specify HDR=No; the provider names your fields F1, F2, etc. Because the Extended Properties string now contains multiple values, it must be enclosed in double quotes itself, plus an additional pair of double quotes to tell Visual Basic to treat the first set of quotes as literal values, as in the following example (where extra spaces have been added for visual clarity).

.ConnectionString = “Data Source=C:\MyFolder\MyWorkbook.xls;” & _”Extended Properties=” ” Excel 8.0; HDR=No;” ” ” Using Microsoft OLE DB Provider for ODBC Drivers The provider for ODBC drivers (which this article refers to as the “ODBC Provider” for the sake of brevity) also requires only two (2) pieces of information in order to connect to an Excel data source: the driver name, and the workbook path and filename.
IMPORTANT: An ODBC connection to Excel is read-only by default. Your ADO Recordset LockType property setting does not override this connection-level setting. You must set ReadOnly to False in your connection string or your DSN configuration if you want to edit your data. Otherwise, you receive the following error message:

Operation must use an updateable query. ODBC Provider Using a DSN-Less Connection String

Dim cn as ADODB.ConnectionSet cn = New ADODB.ConnectionWith cn .Provider = “MSDASQL” .ConnectionString = “Driver={Microsoft Excel Driver (*.xls)};” & _”DBQ=C:\MyFolder\MyWorkbook.xls; ReadOnly=False;” .OpenEnd With ODBC Provider Using a Connection String with a DSN

Dim cn as ADODB.ConnectionSet cn = New ADODB.ConnectionWith cn .Provider = “MSDASQL” .ConnectionString = “DSN=MyExcelDSN;” .OpenEnd With ODBC Provider Using the Data Link Properties Dialog Box
If you use the ADO Data Control or the Data Environment in your application, then the Data Link Properties dialog box is displayed to gather the necessary connection settings. On the Provider tab, select Microsoft OLE DB Provider for ODBC Drivers.On the Connection tab, select the existing DSN that you want to use, or choose Use connection string. This brings up the standard DSN configuration dialog box to gather the necessary connection settings. Remember to deselect the default read-only setting if desired, as mentioned previously.Return to the Connection tab, and click Test Connection. Note that a message box appears informing you that the process has succeeded.Other ODBC Provider Connection Settings
Column headings: By default, it is assumed that the first row of your Excel data source contains columns headings, which can be used as field names. If this is not the case, you must turn this setting off, or your first row of data “disappears” to be used as field names. This is done by adding the optional FirstRowHasNames= setting to the connection string. The default, which does not need to be specified, is FirstRowHasNames=1, where 1 = True. If you do not have column headings, you need to specify FirstRowHasNames=0, where 0 = False; the driver names your fields F1, F2, and so forth. This option is not available in the DSN configuration dialog box.
However, due to a bug in the ODBC driver, specifying the FirstRowHasNames setting currently has no effect. In other words, the Excel ODBC driver (MDAC 2.1 and later) always treats the first row in the specified data source as field names. For additional informationon the Column Heading bug, click the article number below to view the article in the Microsoft Knowledge Base:
288343?(http://support.microsoft.com/kb/288343/EN-US/) BUG: Excel ODBC Driver Disregards the FirstRowHasNames or Header SettingRows to Scan: Excel does not provide ADO with detailed schema information about the data it contains, as a relational database would. Therefore, the driver must scan through at least a few rows of the existing data in order to make an educated guess at the data type of each column. The default for “Rows to Scan” is eight (8) rows. You can specify an integer value from one (1) to sixteen (16) rows, or you can specify zero (0) to scan all existing rows. This is done by adding the optional MaxScanRows= setting to the connection string, or by changing the Rows to Scan setting in the DSN configuration dialog box.
However, due to a bug in the ODBC driver, specifying the Rows to Scan (MaxScanRows) setting currently has no effect. In other words, the Excel ODBC driver (MDAC 2.1 and later) always scans the first 8 rows in the specified data source in order to determine each column’s datatype.
For additional information about the Rows to Scan bug, including a simple workaround, click the article number below to view the article in the Microsoft Knowledge Base:
189897?(http://support.microsoft.com/kb/189897/EN-US/) XL97: Data Truncated to 255 Characters with Excel ODBC DriverOther Settings: If you construct your connection string by using the Data Link Properties dialog box, you may notice some other Extended Properties settings added to the connection string that are not absolutely necessary, such as:

… DefaultDir=C:\WorkbookPath;DriverId=790;FIL=excel 8.0;MaxBufferSize=2048;PageTimeout=5; “Collating Sequence” Error Message in the Visual Basic Editor
In the Visual Basic design environment with certain versions of MDAC, you may see the following error message the first time your program connects to an Excel data source at design time:

Selected collating sequence not supported by the operating system. This message appears only in the IDE and will not appear in the compiled version of the program. For additional information, click the article number below to view the article in the Microsoft Knowledge Base:
246167?(http://support.microsoft.com/kb/246167/EN-US/) PRB: Collating Sequence Error Opening ADODB Recordset the First Time Against an Excel XLSConsiderations That Apply to Both OLE DB ProvidersA Caution about Mixed Data Types
As stated previously, ADO must guess at the data type for each column in your Excel worksheet or range. (This is not affected by Excel cell formatting settings.) A serious problem can arise if you have numeric values mixed with text values in the same column. Both the Jet and the ODBC Provider return the data of the majority type, but return NULL (empty) values for the minority data type. If the two types are equally mixed in the column, the provider chooses numeric over text.
For example: In your eight (8) scanned rows, if the column contains five (5) numeric values and three (3) text values, the provider returns five (5) numbers and three (3) null values. In your eight (8) scanned rows, if the column contains three (3) numeric values and five (5) text values, the provider returns three (3) null values and five (5) text values.In your eight (8) scanned rows, if the column contains four (4) numeric values and four (4) text values, the provider returns four (4) numbers and four (4) null values. As a result, if your column contains mixed values, your only recourse is to store numeric values in that column as text, and to convert them back to numbers when needed in the client application by using the Visual Basic VAL function or an equivalent.
To work around this problem for read-only data, enable Import Mode by using the setting “IMEX=1″ in the Extended Properties section of the connection string. This enforces the ImportMixedTypes=Text registry setting. However, note that updates may give unexpected results in this mode. For additional information about this setting, click the article number below to view the article in the Microsoft Knowledge Base:
194124?(http://support.microsoft.com/kb/194124/EN-US/) PRB: Excel Values Returned as NULL Using DAO OpenRecordsetYou Cannot Open a Password-Protected Workbook
If the Excel workbook is protected by a password, you cannot open it for data access, even by supplying the correct password with your connection settings, unless the workbook file is already open in the Microsoft Excel application. If you try, you receive the following error message:

Could not decrypt file. For additional information, click the article number below to view the article in the Microsoft Knowledge Base:
211378?(http://support.microsoft.com/kb/211378/EN-US/) XL2000: “Could Not Decrypt File” Error with Password Protected File
Retrieve and Edit Excel Data with ADO This section discusses two aspects of working with your Excel data: How to select data -and-
How to change dataHow to Select Data There are several ways to select data. You can:
Select Excel data with code.Select Excel data with the ADO Data control.Select Excel data with Data Environment commands.Select Excel Data with Code Your Excel data may be contained in your workbook in one of the following:
An entire worksheet.A named range of cells on a worksheet.An unnamed range of cells on a worksheet.Specify a Worksheet
To specify a worksheet as your recordsource, use the worksheet name followed by a dollar sign and surrounded by square brackets. For example:

strQuery = “SELECT * FROM [Sheet1$]” You can also delimit the worksheet name with the slanted single quote character (`) found on the keyboard under the tilde (~). For example:

strQuery = “SELECT * FROM `Sheet1$`” Microsoft prefers the square brackets, which are the standing convention for problematic database object names.
If you omit both the dollar sign and the brackets, or just the dollar sign, you receive the following error message:

… the Jet database engine could not find the specified object If you use the dollar sign but omit the brackets, you will see the following error message:

Syntax error in FROM clause. If you try to use ordinary single quotes, you receive the following error message:

Syntax error in query. Incomplete query clause. Specify a Named Range
To specify a named range of cells as your recordsource, simply use the defined name. For example:

strQuery = “SELECT * FROM MyRange” Specify an Unnamed Range
To specify an unnamed range of cells as your recordsource, append standard Excel row/column notation to the end of the sheet name in the square brackets. For example:

strQuery = “SELECT * FROM [Sheet1$A1:B10]” A caution about specifying worksheets: The provider assumes that your table of data begins with the upper-most, left-most, non-blank cell on the specified worksheet. In other words, your table of data can begin in Row 3, Column C without a problem. However, you cannot, for example, type a worksheeet title above and to the left of the data in cell A1.
A caution about specifying ranges: When you specify a worksheet as your recordsource, the provider adds new records below existing records in the worksheet as space allows. When you specify a range (named or unnamed), Jet also adds new records below the existing records in the range as space allows. However, if you requery on the original range, the resulting recordset does not include the newly added records outside the range.
With MDAC versions prior to 2.5, when you specify a named range, you cannot add new records beyond the defined limits of the range, or you receive the following error message:

Cannot expand named range. Select Excel Data with the ADO Data Control After you specify the connection settings for your Excel data source on the General tab of the ADODC Properties dialog box, click on the Recordsource tab. If you choose a CommandType of adCmdText, you can enter a SELECT query in the Command Text dialog box with the syntax described previously. If you choose a CommandType of adCmdTable, and you are using the Jet Provider, the drop-down list displays both the named ranges and worksheet names that are available in the selected workbook, with named ranges listed first.
This dialog box properly appends the dollar sign to worksheet names, but does not add the necessary square brackets. As a result, if you simply select a worksheet name and click OK, you receive the following error message later:

Syntax error in FROM clause. You must manually add the square brackets around the worksheet name. (This combo box does allow editing.) If you are using the ODBC Provider, you see only named ranges listed in this drop-down list. However, you can manually enter a worksheet name with the appropriate delimiters. Select Excel Data with Data Environment Commands After setting up the Data Environment Connection for your Excel data source, create a new Command object. If you choose a Source of Data of SQL Statement, you can enter a query in the textbox using the syntax described previously. If you choose a Source of Data of Database Object, select Table in the first drop-down list, and you are using the Jet Provider, the drop-down list displays both named ranges and worksheet names available in the selected workbook, with named ranges listed first. (If you choose a worksheet name in this location, you do not need to add square brackets around the worksheet name manually as you do for the ADO Data Control.) If you are using the ODBC Provider, you see only named ranges listed in this drop-down list. However, you can manually enter a worksheet name. How to Change Excel Data: Edit, Add, and DeleteEdit
You can edit Excel data with the normal ADO methods. Recordset fields which correspond to cells in the Excel worksheet containing Excel formulas (beginning with “=”) are read-only and cannot be edited. Remember that an ODBC connection to Excel is read-only by default, unless you specify otherwise in your connection settings. See earlier under “Using the Microsoft OLE DB Provider for ODBC Drivers.”
Add
You can add records to your Excel recordsource as space allows. However, if you add new records outside the range that you originally specified, these records are not visible if you requery on the original range specification. See earlier under “A caution about specifying ranges.”
In certain circumstances, when you use the AddNew and Update methods of the ADO Recordset object to insert new rows of data into an Excel table, ADO may insert the data values into the wrong columns in Excel. For additional information, click the article number below to view the article in the Microsoft Knowledge Base:
314763?(http://support.microsoft.com/kb/314763/EN-US/) FIX: ADO Inserts Data into Wrong Columns in ExcelDelete
You are more restricted in deleting Excel data than data from a relational data source. In a relational database, “row” has no meaning or existence apart from “record”; in an Excel worksheet, this is not true. You can delete values in fields (cells). However, you cannot: Delete an entire record at once or you receive the following error message:

Deleting data in a linked table is not supported by this ISAM. You can only delete a record by blanking out the contents of each individual field.Delete the value in a cell containing an Excel formula or you receive the following error message:

Operation is not allowed in this context. You cannot delete the empty spreadsheet row(s) in which the deleted data was located, and your recordset will continue to display empty records corresponding to these empty rows.A caution about editing Excel data with ADO: When you insert text data into Excel with ADO, the text value is preceded with a single quote. This may cause problems later in working with the new data.
Retrieve Data Source Structure (Metadata) from Excel You can retrieve data about the structure of your Excel data source (tables and fields) with ADO. Results differ slightly between the two OLE DB Providers, although both return at least the same small number of useful fields of information. This metadata can be retrieved with the OpenSchema method of the ADO Connection object, which returns an ADO Recordset object. You can also use the more powerful Microsoft ActiveX Data Objects Extensions for Data Definition Language and Security (ADOX) library for this purpose. In the case of an Excel data source however, where a “table” is either a worksheet or a named range, and a “field” is one of a limited number of generic datatypes, this additional power is not useful. Query Table Information Of the various objects available in a relational database (tables, views, stored procedures, and so forth), an Excel data source exposes only table equivalents, consisting of the worksheets and the named ranges defined in the specified workbook. Named ranges are treated as “Tables” and worksheets are treated as “System Tables,” and there is not much useful table information you can retrieve beyond this “table_type” property. You request a list of the available tables in the workbook with the following code:

Set rs = cn.OpenSchema(adSchemaTables) The Jet Provider returns a recordset with nine (9) fields, of which it populates only four (4):
table_nametable_type (“Table” or “System Table”)date_created date_modified The two date fields for a given table always show the same value, which appears to be the “date last modified.” In other words, “date_created” is not reliable.
The ODBC Provider also returns a recordset with nine (9) fields, of which it populates only three (3):
table_catalog, the folder in which the workbook is located.table_name.table_type, as noted earlier. According to the ADO documentation, it is possible to retrieve a list of worksheets only, for example, by specifying the following additional criteria to the OpenSchema method:

Set rs = cn.OpenSchema(adSchemaTables, Array(Empty, Empty, Empty, “System Table”)) Unfortunately, this does not work against an Excel data source with MDAC versions later than 2.0, using either provider. Query Field Information Every field (column) in an Excel data source is one of the following datatypes:
numeric (ADO datatype 5, adDouble)currency (ADO datatype 6, adCurrency)logical or boolean (ADO datatype 11, adBoolean)date (ADO datatype 7, adDate, using Jet; 135, adDBTimestamp, using ODBC)text (an ADO ad…Char type, such as 202, adVarChar, 200, adVarWChar or similar) The numeric_precision for a numeric column is always returned as 15 (which is the maximum precision in Excel); the character_maximum_length of a text column is always returned as 255 (which is the maximum display width, but not the maximum length, of text in an Excel column). There is not much useful field information that you can obtain beyond the data_type property. You request a list of the available fields in a table with the following code:

Set rs = cn.OpenSchema(adSchemaTables, Array(Empty, Empty, “TableName”, Empty)) The Jet Provider returns a recordset that contains 28 fields, of which it populates eight (8) for numeric fields and nine (9) for text fields. The useful fields are likely to be these:
table_namecolumn_nameordinal_positiondata_type The ODBC Provider returns a recordset containing 29 fields, of which it populates ten (10) for numeric fields and 11 for text fields. The useful fields are the same as earlier. Enumerate Tables and Fields and Their Properties Visual Basic code (such as the following sample) can be used to enumerate the tables and columns in an Excel data source and the available fields of information about each. This sample outputs its results to a Listbox, List1, on the same form.

Dim cn As ADODB.ConnectionDim rsT As ADODB.RecordsetDim intTblCnt As Integer, intTblFlds As IntegerDim strTbl As StringDim rsC As ADODB.RecordsetDim intColCnt As Integer, intColFlds As IntegerDim strCol As StringDim t As Integer, c As Integer, f As IntegerSet cn = New ADODB.ConnectionWith cn .Provider = “Microsoft.Jet.OLEDB.4.0″ .ConnectionString = “Data Source=” & App.Path & _”\ExcelSrc.xls;Extended Properties=Excel 8.0;” ‘.Provider = “MSDASQL” ‘.ConnectionString = “Driver={Microsoft Excel Driver (*.xls)};” & _”DBQ=” & App.Path & “\ExcelSrc.xls; ” .CursorLocation = adUseClient .OpenEnd WithSet rsT = cn.OpenSchema(adSchemaTables)intTblCnt = rsT.RecordCountintTblFlds = rsT.Fields.CountList1.AddItem “Tables: ” & intTblCntList1.AddItem “——————–”For t = 1 To intTblCnt strTbl = rsT.Fields(“TABLE_NAME”).Value List1.AddItem vbTab & “Table #” & t & “: ” & strTbl List1.AddItem vbTab & “——————–” For f = 0 To intTblFlds – 1 List1.AddItem vbTab & rsT.Fields(f).Name & _vbTab & rsT.Fields(f).Value Next List1.AddItem “——————–” Set rsC = cn.OpenSchema(adSchemaColumns, Array(Empty, Empty, strTbl, Empty)) intColCnt = rsC.RecordCount intColFlds = rsC.Fields.Count For c = 1 To intColCnt strCol = rsC.Fields(“COLUMN_NAME”).Value List1.AddItem vbTab & vbTab & “Column #” & c & “: ” & strCol List1.AddItem vbTab & vbTab & “——————–” For f = 0 To intColFlds – 1 List1.AddItem vbTab & vbTab & rsC.Fields(f).Name & _vbTab & rsC.Fields(f).Value Next List1.AddItem vbTab & vbTab & “——————–” rsC.MoveNext Next rsC.Close List1.AddItem “——————–” rsT.MoveNextNextrsT.Closecn.Close Use the Data View Window If you create a data link to an Excel data source in the Visual Basic Data View window, the Data View window displays the same information that you can retrieve programmatically as described earlier. In particular, note that the Jet Provider lists both worksheets and named ranges under “Tables,” where the ODBC Provider shows only named ranges. If you are using the ODBC Provider and have not defined any named ranges, the “Tables” list will be empty. Excel Limitations The use of Excel as a data source is bound by the internal limitations of Excel workbooks and worksheets. These include, but are not limited to:
Worksheet size: 65,536 rows by 256 columnsCell contents (text): 32,767 charactersSheets in a workbook: limited by available memoryNames in a workbook: limited by available memory

How To Modify the Visual Data Manager (VISDATA) to Work with Access 2000 Databases

Symptoms
Microsoft Visual Basic ships with an add-in utility known as the Visual Data Manager (VISDATA) for which source code is also provided in the form of a sample project named Visdata.vbp. Visdata.vbp is installed with other Visual Basic samples as part of the MSDN Library installation.
This article describes how to modify the source code for the Visual Data Manager add-in in order to use the add-in with Microsoft Access 2000 format database files.

Resolution
Adapting VISDATA to work with Microsoft Access 2000 format databases requires changing only one project reference, adding one menu item, and adding one line of code to process the new menu item.
Update the DAO Reference from DAO 3.51 to DAO 3.60. (This step alone is sufficient to allow you to open and work with Access 2000 files.)Open Visdata.vbp in the Visual Basic design environment.On the Project menu, open the list of References.Deselect the existing reference to Microsoft Data Access Objects 3.51, and then locate and select Microsoft Data Access Objects 3.60. If you are using Visual Basic 6.0, be sure to move the DAO 3.6 reference above the ADO library reference in the list.Add a new menu item and code to allow creating a new Access 2000 database.Open the main form, frmMDI, in the design environment.From the Tools menu, open the Menu Editor.In the Menu Editor window, scroll down in the existing menu items to File / New / Microsoft Access.In order to insert the new menu item after the existing entry for Access Version 7.0 MDB files, select the following entry: dBase. Click the Insert button, and then click the RIGHT ARROW button to make the new, blank entry a subitem under the Microsoft Access heading. Enter Access 2000 as the Caption and mnuDBNMDB2K as the Name. Close the Menu Editor by clicking OK.Open the frmMDI code module and select the mnuDBNMDB2K_Click event procedure in the drop-down list. Enter the following line of code:

NewMDB dbVersion40In Visual Basic 6.0 only, update ADO connection strings to support Access 2000.VisData uses both DAO and ADO. Use the Search function on the Visual Basic Edit menu to locate all references in the project to the Microsoft Jet OLE DB Provider version 3.51 and update 3.51 to 4.0.In Visual Basic 6.0 only, add code that will enable the Grid toolbar button, which displays a table of records in a DBGrid control rather than one record per form.Open the module modVisData and find the OpenTable procedure.After the lines:

If gsDataType = gsMSACCESS Then.ConnectionString = “PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=” & gsDBName insert the additional line:

.CursorLocation = adUseClient Then open frmDataGrid and find the Form_Load event procedure.After the line:

Set datDataCtl.Recordset = mrsFormRecordset insert the additional lines:

datDataCtl.RefreshSet grdDataGrid.DataSource = datDataCtlgrdDataGrid.Refresh If you were to omit this step, you might see an empty grid; or the grid may display with the very first cell empty.Recompile the VISDATA project and copy the compiled executable to the Visual Basic directory (which is \Program Files\Microsoft Visual Studio\Vb98 by default in Visual Basic 6.0).