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 for November, 2011

How to automate Excel from Visual Basic .NET to fill or to obtain data in a range by using arrays

Symptoms
This article demonstrates how to automate Microsoft Excel and how to fill a multi-cell range with an array of values. This article also illustrates how to retrieve a multi-cell range as an array by using Automation.
Resolution
To fill a multi-cell range without populating cells one at a time, you can set the Value property of a Range object to a two-dimensional array. Likewise, a two-dimensional array of values can be retrieved for multiple cells at once by using the Value property. The following steps demonstrate this process for both setting and retrieving data using two-dimensional arrays. Build the Automation Client for Microsoft ExcelStart Microsoft Visual Studio .NET.On the File menu, click New, and then click Project. Select Windows Application from the Visual Basic Project types. By default, Form1 is created.Add a reference to Microsoft Excel Object Library. To do this, follow these steps: On the Project menu, click Add Reference.On the COM tab, locate Microsoft ExcelObject Library, and then click Select.
Note Microsoft Office 2007 and Microsoft Office 2003 include Primary Interop Assemblies (PIAs). Microsoft Office XP does not include PIAs, but they can be downloaded.
For additional information about Office XP PIAs, click the article number below to view the article in the Microsoft Knowledge Base:
328912?(http://support.microsoft.com/kb/328912/EN-US/) INFO: Microsoft Office XP PIAs Are Available for DownloadClick OK in the Add References dialog box to accept your selections. If you are prompted to generate wrappers for the libraries that you selected, click Yes.On the View menu, select Toolbox to display the Toolbox. Add two buttons and a check box to Form1.Set the Name property for the check box to FillWithStrings.Double-click Button1. The code window for the Form appears.Add the following to the top of Form1.vb:

Imports Microsoft.Office.Interop In the code window, replace the following code

Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.ClickEnd Sub with:

‘Keep the application object and the workbook object global, so you can’retrieve the data in Button2_Click that was set in Button1_Click.Dim objApp As Excel.ApplicationDim objBook As Excel._WorkbookPrivate Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.ClickDim objBooks As Excel.WorkbooksDim objSheets As Excel.SheetsDim objSheet As Excel._WorksheetDim range As Excel.Range’ Create a new instance of Excel and start a new workbook.objApp = New Excel.Application()objBooks = objApp.WorkbooksobjBook = objBooks.AddobjSheets = objBook.WorksheetsobjSheet = objSheets(1)’Get the range where the starting cell has the address’m_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.range = objSheet.Range(“A1″, Reflection.Missing.Value)range = range.Resize(5, 5)If (Me.FillWithStrings.Checked = False) Then’Create an array.Dim saRet(5, 5) As Double’Fill the array.Dim iRow As LongDim iCol As LongFor iRow = 0 To 5For iCol = 0 To 5′Put a counter in the cell.saRet(iRow, iCol) = iRow * iColNext iColNext iRow’Set the range value to the array.range.Value = saRetElse’Create an array.Dim saRet(5, 5) As String‘Fill the array.Dim iRow As LongDim iCol As LongFor iRow = 0 To 5For iCol = 0 To 5′Put the row and column address in the cell.saRet(iRow, iCol) = iRow.ToString() + “|” + iCol.ToString()Next iColNext iRow’Set the range value to the array.range.Value = saRetEnd If’Return control of Excel to the user.objApp.Visible = TrueobjApp.UserControl = True’Clean up a little.range = NothingobjSheet = NothingobjSheets = NothingobjBooks = NothingEnd Sub Return to the design view for Form1, and then double-click Button2.In the code window, replace the following code

Private Sub Button2_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button2.ClickEnd Sub with:

Private Sub Button2_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button2.ClickDim objSheets As Excel.SheetsDim objSheet As Excel._WorksheetDim range As Excel.Range’Get a reference to the first sheet of the workbook.On Error Goto ExcelNotRunningobjSheets = objBook.WorksheetsobjSheet = objSheets(1)ExcelNotRunning:If (Not (Err.Number = 0)) ThenMessageBox.Show(“Cannot find the Excel workbook.Try clicking Button1 to ” + _”create an Excel workbook with data before running Button2.”, _”Missing Workbook?”)’We cannot automate Excel if we cannot find the data we created,’so leave the subroutine.Exit SubEnd If’Get a range of data.range = objSheet.Range(“A1″, “E5″)’Retrieve the data from the range.Dim saRet(,) As ObjectsaRet = range.Value’Determine the dimensions of the array.Dim iRows As LongDim iCols As LongiRows = saRet.GetUpperBound(0)iCols = saRet.GetUpperBound(1)’Build a string that contains the data of the array.Dim valueString As StringvalueString = “Array Data” + vbCrLfDim rowCounter As LongDim colCounter As LongFor rowCounter = 1 To iRowsFor colCounter = 1 To iCols’Write the next value into the string.valueString = String.Concat(valueString, _saRet(rowCounter, colCounter).ToString() + “, “)Next colCounter’Write in a new line.valueString = String.Concat(valueString, vbCrLf)Next rowCounter’Report the value of the array.MessageBox.Show(valueString, “Array Values”)’Clean up a little.range = NothingobjSheet = NothingobjSheets = NothingEnd Sub Test the Automation ClientPress F5 to build and to run the sample program.Click Button1. Microsoft Excel is started with a new workbook, and cells A1:E5 of the first worksheet are populated with numeric data from an array.Click Button2. The program retrieves the data in cells A1:E5 into a new array and displays the results in a message box.Select FillWithStrings, and then click Button1 to fill cells A1:E5 with the string data.

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.

How To Find and Highlight Text in the RichTextBox Control

Symptoms
In many applications there is a function to search and highlight keywordsin a text window. The RichTextBox control in Visual Basic can be madeto provide this functionality, as shown in the sample code below.
Resolution
Start a new project in Visual Basic. Form1 is created by default.Place a Command button and a RichTextBox on Form1. Set the Text propertyof the RichTextBox to “This is an example of finding text in a richtext box.”Add the following code to the General Declarations section of Form1:

Option ExplicitPrivate Sub Command1_Click()HighlightWords RichTextBox1, “text”, vbRedEnd SubPrivate Function HighlightWords(rtb As RichTextBox, _sFindString As String, _lColor As Long) _As IntegerDim lFoundPos As Long’Position of first character’of matchDim lFindLength As Long’Length of string to findDim lOriginalSelStart As LongDim lOriginalSelLength As LongDim iMatchCount As Integer’Number of matches’Save the insertion points current location and lengthlOriginalSelStart = rtb.SelStartlOriginalSelLength = rtb.SelLength’Cache the length of the string to findlFindLength = Len(sFindString)’Attempt to find the first matchlFoundPos = rtb.Find(sFindString, 0, , rtfNoHighlight)While lFoundPos > 0iMatchCount = iMatchCount + 1rtb.SelStart = lFoundPos’The SelLength property is set to 0 as’soon as you change SelStartrtb.SelLength = lFindLengthrtb.SelColor = lColor’Attempt to find the next matchlFoundPos = rtb.Find(sFindString, _lFoundPos + lFindLength, , rtfNoHighlight)Wend’Restore the insertion point to its original’location and lengthrtb.SelStart = lOriginalSelStartrtb.SelLength = lOriginalSelLength’Return the number of matchesHighlightWords = iMatchCountEnd Function Choose Start from the Run menu, or press the F5 key to start theproject. Click the Command button and you should see that bothoccurrences of the word “text” are now shown in red.