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 ‘name’

PRB: Type Mismatch with Default Prop of VB4 Data Access Object

Symptoms
Some data access objects in Visual Basic for Windows version 4.0 no longerhave the default “Name” property. Instead, these objects now have a defaultcollection. This change can lead to “Type Mismatch” (Error 13) or “InvalidArgument” (Error 3001) errors when attempting to run your code.
Resolution
To work around this problem, add the name of the property you want toreference.
For example, use this:

MsgBox Data1.Database.TableDefs(0).Name instead of this:

MsgBox Data1.Database.TablesDefs(0)

PRB: Run-time Error Message 3024 Using SQL and DAO Against Oracle

Symptoms
If you try to run Structured Query Language (SQL) against an Oracledatabase through Data Access Objects (DAO), you can encounter the followingerror:

Run-Time Error 3024
Couldn’t find file C:\Program Files\DevStudio\VB\<schema name>.mdb.This error occurs when you try to specify a schema name in your SQLstatement and you use DAO with Oracle. The <schema name> in the errormessage is whatever schema name you specified for the Oracle object youreference.
Resolution
If you add the dbSQLPassThrough option to the OpenRecordset method, thesample code in the MORE INFORMATION section of this article runs withouterror. You can use brackets ([ ]) around the table name in the SQL string toavoid the error as well:

sql = “SELECT * FROM [scott.emp]” Also, you can use an advanced data access technology, such as ActiveX DataObjects (ADO) to avoid this error.

BUG: Data Form Wizard Mishandles ‘-’ in Table or Field Names

Symptoms
When loading a form created by the Data Form Wizard, you may receive one ofthe following error messages:

Run-time error ‘-214217900 (80040e14)’, “Syntax error in FROM clause”
-or-

Run-time error ‘-214217904 (80040e10)’, “No value given for one or morerequired parameters”
Resolution
If the data source for a form created by the Data Form Wizard containsa dash ‘-’ in its name or in the name of a field, it is required that thedata source name or field name be delimited by brackets in a SQL statement.The Data Form Wizard does not include brackets around these names.

BUG: “Invalid Property Data” Error While Creating OracleCommand in Visual Studio .NET 2003

Symptoms
When you create a command object for Oracle to run a stored procedure by using the OracleCommand object from the Toolbox, you may receive the following error message after you specify the stored procedure name in the CommandText property:

Invalid Property Data
The stored procedure “OraclePackageName.OracleProcedureName” could not be found in the database.
Resolution
To work around this problem, use one of the following methods: In the CommandText property of OracleCommand1, type the name of the stored procedure exactly as it appears (this property is case-sensitive) in the stored procedure list in Server Explorer.Click OK to ignore the error message, and then manually add the code to call the Oracle stored procedure in your class. You can view the name of the stored procedure in Server Explorer. To do this, follow these steps: On the View menu, click Server Explorer.Right-click Data Connection, and then click Add Connection.On the Provider tab, click to select the Microsoft OLE DB Provider for Oracle check box. Click the Connection tab. Type the server name, the user name and the password, and then click Test Connection. Click OK to close the Test connection succeeded dialog box. Click OK to close the Data Link Properties dialog box. Expand Oracle database. Expand Stored Procedure to view the list of existing stored procedures.

How To Use ADO to Access Objects Through an ADSI LDAP Provider

Symptoms
The Active Directory Service Interfaces (ADSI) LightweightDirectory Access Protocol (LDAP) provider implements OLE DB interfaces thatallow you to use ActiveX Data Objects (ADO) to access objects in LDAPcompliant directories. You must create an ADO connection object and set itsProvider property to “ADsDSOObject”.You can specify any string, including”", as the connection string (first argument) of the ADO connectionobject’s open method.
The connection object Execute method’s CommandText (first object) is anLDAP query composed of four elements separated by semicolons, in thefollowing format:

<LDAP://server/adsidn>;ldapfilter;attributescsv;scope where:
server is the name (or IP address) of the server hosting the directory.adsidn is the distinguished name (DN) of the starting point for yourquery expressed ADsPath format with “/” separators and the root of thenamespace to the left. You can also use an X.500 style attributed nameformat with the relative distinguished names separated by commas and theroot of the name space to the right.1dap filter is the LDAP filter string (see rfc2254).attributescsv is a comma separated list of names of the attributes to be returned for each row in the recordset.scope is either: base, onelevel, or subtree.NOTE: rfc2253 specifies the LDAP syntaxes on which the ADSI LDAP syntax is based.
To return the ADsPath, class, and cn attributes of all the objects in allthe recipient containers in an Exchange server, you can use the followingCommandText (in URL format):

LDAP:<//server/o=organization/ou=site/cn=recipients>;(objectClass=*);ADsPath,objectClass,cn;subtree” or (in attributed name format):

<LDAP://server/cn=recipients,ou=site,o=organization>, _(objectClass=*);ADsPath,objectClass;subtree
Resolution
The following Visual Basic sample code illustrates this query:
Sample Code

Dim conn As ADODB.ConnectionDim rs As ADODB.RecordsetSet conn = New ADODB.Connectionconn.Provider = “ADSDSOObject”conn.Open “ADs Provider”Set rs = conn.Execute( _”<LDAP://server/o=organization/ou=site/cn=recipients>;” _& “(objectClass=*);ADsPath,objectClass,cn;subtree”)While Not rs.EOFDebug.Print rs.Fields(0).Value, rs.Fields(1).Value, _rs.Fields(2).Valuers.MoveNextWendconn.Close

How to automate Word with Visual Basic to create a Mail Merge

Symptoms
This article discusses how to automate Word to create a mail merge for an external data source. This article also explains the code differences between accessing the data with OLEDB, ODBC, and dynamic data exchange (DDE).
Resolution
Data access methods To programmatically set up a data source for a Word mail merge document, you first call the OpenDataSource method of a MailMerge object. The syntax for the OpenDataSource method is as follows:
<MailMergeObject>.OpenDataSource(Name, [Format], [ConfirmConversions], [ReadOnly], [LinkToSource], [AddToRecentFiles], [PasswordDocument], [PasswordTemplate], [Revert],[WritePasswordDocument], [WritePasswordTemplate], [Connection], [SQLStatement], [SQLStatement1], [OpenExclusive], [SubType]) Note For a complete description of each argument, refer to the Microsoft Word Visual Basic online Help. Of primary interest for connecting to an external data source are the Name, Connection, and SubType arguments. Different combinations of these three arguments represent different data access methods for the mail merge.
Using OLEDB OLEDB is the recommended data access method. To specify OLEDB as the data access method with OpenDataSource, supply the Name argument with the path and the file name to either the database or an Office DataSource Connection (.odc). If you provide a database for the Name argument, Word will automatically use OLEDB if there is an OLEDB provider installed that supports the database format.
Example

<MailMergeObject>.OpenDataSource Name:=”C:\MyDB.mdb”, _SQLStatement:=”SELECT * FROM [MyTable]”
- or -

<MailMergeObject>.OpenDataSource Name:=”C:\MyDataSource.odc”, _SQLStatement:=”SELECT * FROM [MyTable]” Word and other Office XP applications use the Office DataSource Object (ODSO) for OLEDB access to external data sources. ODSO is the only mechanism by which Word can access data by using OLEDB for a mail merge. ODSO requires that the Name argument for OpenDataSource be either a complete path to a database or a complete path to a valid ODC file. ODSO ignores any information in the Connection argument.
Using ODBC You can use ODBC for your mail merge to access data for which a user data source name (DSN) has been set up on the system. To specify ODBC as the data access method with OpenDataSource, supply an empty string for the Name argument, an ODBC connection string for the Connection argument, and wdMergeSubTypeWord2000 for the SubType argument.
Example

<MailMergeObject>.OpenDataSource Name:= “”, _Connection:= “DSN=MySQLServerDSN;DATABASE=pubs;uid=sa;pwd=;”, _SQLStatement:= “Select au_id, au_lname, au_fname from authors”, _SubType:= wdMergeSubTypeWord2000
Using DDE You can use DDE to access data in Microsoft Access databases or Microsoft Excel workbooks. To specify DDE as the data access method with OpenDataSource, supply the path and the file name to the database or the workbook for the Name argument, and wdMergeSubTypeWord2000 for the SubType argument.
Example

<MailMergeObject>.OpenDataSource Name:=”C:\MyDB.mdb”, _SQLStatement:=”SELECT * FROM [MyTable]“, _SubType:=wdMergeSubTypeWord2000
Automation sample The following sample code creates and executes a mail merge for form letters by using OLEDB (by way of ODSO). The data source that is used is the sample Access database Northwind.mdb. If Northwind is not installed, start Microsoft Access 2002 or Microsoft Office Access 2003. On the Help menu, click Sample Databases, and then choose Northwind Sample Database to install this feature.
To run this sample, follow these steps: Start a new Standard EXE project in Visual Basic. By default, Form1 is created.On the Project menu, click References.Click Microsoft Word 2000 Object Library in the list of references, and then click OK.
Note: To use the Microsoft Office Word 2003 Object, add the Microsoft Word 11.0 Object Library in the list of references and then Click OK.Add a CommandButton control to Form1.Add the following code to the code module for Form1.
Note If it is necessary, modify the path to Northwind.mdb to match your installation for Office XP.

Dim WithEvents oApp As Word.ApplicationPrivate Sub Form_Load()’Start Word.Set oApp = CreateObject(“Word.Application“)End SubPrivate Sub Command1_Click()Dim oMainDoc As Word.DocumentDim oSel As Word.SelectionDim sDBPath as String’Start a new main document for the mail merge.Set oMainDoc = oApp.Documents.AddWith oMainDoc.MailMerge.MainDocumentType = wdFormLetters’Set up the mail merge data source to Northwind.mdb.sDBPath = “C:\Program Files\Microsoft Office\” & _”OfficeXP\Samples\Northwind.mdb”.OpenDataSource Name:=sDBPath, _SQLStatement:=”SELECT * FROM [Customers]“‘Add the field codes to the document to create the form letter.With .FieldsSet oSel = oApp.Selection.Add oSel.Range, “CompanyName”oSel.TypeParagraph.Add oSel.Range, “Address”oSel.TypeParagraph.Add oSel.Range, “City”oSel.TypeText “, “.Add oSel.Range, “Country”oSel.TypeParagraphoSel.TypeParagraphoSel.TypeText “Dear “.Add oSel.Range, “ContactName”oSel.TypeText “,”oSel.TypeParagraphoSel.TypeParagraphoSel.TypeText ” This letter is to inform you…”oSel.TypeParagraphoSel.TypeParagraphoSel.TypeText “Sincerely, [Your Name Here]“End WithEnd With’Perform the mail merge to a new document.With oMainDoc.MailMerge.Destination = wdSendToNewDocument.MailMerge.Execute Pause:=FalseEnd WithEnd SubPrivate Sub oApp_MailMergeAfterMerge(ByVal Doc As Word.Document, ByVal DocResult As Word.Document)’When the mail merge is complete, 1) make Word visible,’2) close the mail merge document leaving only the resulting document’open and 3) display a message.Doc.Close FalseoApp.Visible = TrueMsgBox “Mail Merge Complete: ” & oApp.ActiveDocument.NameEnd SubPrivate Sub Form_Unload(Cancel As Integer)Set oApp = NothingEnd Sub Press F5 to run the program.Click the CommandButton control on Form1 to perform the mail merge. When the code completes, Word is made visible with a new document open. The new document contains form letters that result from a mail merge containing data that is extracted from the Customers table in Northwind.mdb.