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 the ‘Uncategorized’ Category

Best Online health insurance quotes

Compare health insurance quotes to find the best deal for you can be done through HealthInsuranceQuotes.org. They offer several quotes of insurance by the page of the nations top insurance providers and other information necessary to make informed decisions about your health care coverage.

Health is wealth, but did you know that your health is also an investment. According to HealthInsuranceQuotes.org: Your health is the most important investment you ever make in your life. So, be questions, how this could be true? But if correctly done, that our health a lifetime increased depending on the HealthInsuranceQuotes.org value. Imagine if you could sell your health in the future, or will it to Inheritors If their ‘ future is estimated. Therefore, you do your investment decisions with a health insurance is sufficient enough, add to your future medical needs.

The insurance industry is of large companies, and like many other companies – insurance providers competition for enterprises of all clients that they encounter. Many people have tried to HealthInsuranceQuotes.org to understand why the comparison shopping for the best health insurance quote is a plus. With easy search system to use, you can find health insurance rates that are affordable for you, without sacrificing time and money. This is the advantage of HealthInsuranceQuotes.org, for anyone needing more affordable insurance.

The top-rated insurance companies can offer cheaper coverage. You can expect low cost quotes from insurance companies that have solid reputations in the industry. Moreover, health insurance isn’t there just to protect people in accidents, it is also there to cover day to day needs. Such as, eye care, oral care, and prescription drugs. Many policies have limited coverage for these areas, and the patient is expected to pay out of pocket also. For this reason, supplemental health insurance coverage is best to ensure payment of unexpected medical bills, as needed. The self employed can also benefit from online health insurance quotes. Many companies can adjust your health insurance plan to only the services that you need. Finally, if you’ve been laid-off, then COBRA subsidy is designed to help you pay for health insurance during your unemployment. Also, it pays up to 65% of the cost of your COBRA premiums. The subsidy lasts up to 15 months, an 3 months after that -but you will pay 100% of the premiums. When, COBRA is cancelled, seek other coverage!

Church digital signage solutions for motivating congregations

Modern churches are constantly the methods to attract the attention and to ensure that local communities are aware on the upcoming events in the calendar Church, making use of signage digital Church.

Generally churches have convey messages on posters, static billboards, and boards pass message to everyone, but for now, even bill you for the growth of the Church in the free digital signage, because it helps much.

Digital display to the Church

Church in the free digital signage is used to communicate with the Congregation in most of the churches and they are very helpful in spreading the message of God through this digital advertising.

Outdoor digital signage has many advantages over various mediums. A church digital advertising screen is scheduled to really the content on specific times.adn when the service of the congregation is arrived then the messages can be displayed. The messages are thus well spread with the help of church digital signage solutions. This will really help in spreading messages and to encourage other people to joint in the community as well.

How To Pass String Data Between Applications Using SendMessage

Symptoms
There are many ways to achieve inter-process communication using VisualBasic. Unless you establish an OLE Automation client server relationship,string data is difficult to handle cleanly. The main reason is that 32-bitapplications run in a separate address space, so the address of a string inone application is not meaningful to another application in a differentaddress space. Using the SendMessage() API function to pass a WM_COPYDATAmessage avoids this problem.
This article demonstrates how to pass string data from one application toanother by using the SendMessage API function with the WM_COPYDATA message.
Resolution
WARNING: One or more of the following functions are discussed in this article; VarPtr, VarPtrArray, VarPtrStringArray, StrPtr, ObjPtr. These functions are not supported by Microsoft Technical Support. They are not documented in the Visual Basic documentation and are provided in this Knowledge Base article “as is.” Microsoft does not guarantee that they will be available in future releases of Visual Basic.
Visual Basic does not support pointers and castings in the manner of VisualC++. In order to pass string data from one Visual Basic application toanother, the Unicode string must be converted to ASCII prior to passing itto the other application. The other application must then convert the ASCIIstring back to Unicode.
The following summarizes how to pass string data from one application toanother.
Step-by-Step Example Convert the string to a byte array using the CopyMemory() API.Obtain the address of the byte array using the VarPtr() intrinsicfunction and copy the address and length of the byte array into a COPYDATASTRUCT structure.Pass the COPYDATASTRUCT to another application using the WM_COPYDATAmessage, setting up the other application to receive the message.Unpack the structure on the target system using CopyMemory(), andconvert the byte array back to a string using the StrConv() intrinsicfunction.The next section shows you how to create a sample program that demonstratespassing string data from one application to another.
Steps to Create the SampleTo create this sample, you create two separate projects; a sendingproject and a target project.
Create the target application:Start a new Standard EXE project in Visual Basic. Form1 is created by default. This project will be your target application.Add a Label control to Form1.Copy the following code to the Code window of Form1:

Private Sub Form_Load()gHW = Me.hWndHookMe.Caption = “Target”Me.ShowLabel1.Caption = Hex$(gHW)End SubPrivate Sub Form_Unload(Cancel As Integer)UnhookEnd Sub Add a module to the project and paste the following code in the Module1 code window:

Type COPYDATASTRUCTdwData As LongcbData As LonglpData As LongEnd TypePublic Const GWL_WNDPROC = (-4)Public Const WM_COPYDATA = &H4AGlobal lpPrevWndProc As LongGlobal gHW As Long’Copies a block of memory from one location to another.Declare Sub CopyMemory Lib “kernel32″ Alias “RtlMoveMemory” _(hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)Declare Function CallWindowProc Lib “user32″ Alias _”CallWindowProcA” (ByVal lpPrevWndFunc As Long, ByVal hwnd As _Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As _Long) As LongDeclare Function SetWindowLong Lib “user32″ Alias “SetWindowLongA” _(ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As _Long) As LongPublic Sub Hook()lpPrevWndProc = SetWindowLong(gHW, GWL_WNDPROC, _AddressOf WindowProc)Debug.Print lpPrevWndProcEnd SubPublic Sub Unhook()Dim temp As Longtemp = SetWindowLong(gHW, GWL_WNDPROC, lpPrevWndProc)End SubFunction WindowProc(ByVal hw As Long, ByVal uMsg As Long, _ByVal wParam As Long, ByVal lParam As Long) As LongIf uMsg = WM_COPYDATA ThenCall mySub(lParam)End IfWindowProc = CallWindowProc(lpPrevWndProc, hw, uMsg, wParam, _lParam)End FunctionSub mySub(lParam As Long)Dim cds As COPYDATASTRUCTDim buf(1 To 255) As ByteCall CopyMemory(cds, ByVal lParam, Len(cds))Select Case cds.dwDataCase 1Debug.Print “got a 1″Case 2Debug.Print “got a 2″Case 3Call CopyMemory(buf(1), ByVal cds.lpData, cds.cbData)a$ = StrConv(buf, vbUnicode)a$ = Left$(a$, InStr(1, a$, Chr$(0)) – 1)Form1.Print a$End SelectEnd Sub Save the project and minimize the Visual Basic IDE.
Create the Sending ApplicationStart a second instance of the Visual Basic IDE and create a new Standard EXE project in Visual Basic. Form1 is created by default.Add a CommandButton to Form1.Copy the following code to the Code window of Form1:

Private Type COPYDATASTRUCTdwData As LongcbData As LonglpData As LongEnd TypePrivate Const WM_COPYDATA = &H4APrivate Declare Function FindWindow Lib “user32″ Alias _”FindWindowA” (ByVal lpClassName As String, ByVal lpWindowName _As String) As LongPrivate Declare Function SendMessage Lib “user32″ Alias _”SendMessageA” (ByVal hwnd As Long, ByVal wMsg As Long, ByVal _wParam As Long, lParam As Any) As Long’Copies a block of memory from one location to another.Private Declare Sub CopyMemory Lib “kernel32″ Alias “RtlMoveMemory” _(hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)Private Sub Command1_Click()Dim cds As COPYDATASTRUCTDim ThWnd As LongDim buf(1 To 255) As Byte’ Get the hWnd of the target applicationThWnd = FindWindow(vbNullString, “Target”)a$ = “It Works!”‘ Copy the string into a byte array, converting it to ASCIICall CopyMemory(buf(1), ByVal a$, Len(a$))cds.dwData = 3cds.cbData = Len(a$) + 1cds.lpData = VarPtr(buf(1))i = SendMessage(ThWnd, WM_COPYDATA, Me.hwnd, cds)End SubPrivate Sub Form_Load()’ This gives you visibility that the target app is running’ and you are pointing to the correct hWndMe.Caption = Hex$(FindWindow(vbNullString, “Target”))End Sub Save the project.
Running the SampleRestore the target application and press the F5 key to run the project. Note that the value of the hWnd displayed in the label.Restore the sending application and press the F5 key to run the project.Verify that the hWnd in the form caption matches the hWnd in the labelon the target application. Click the CommandButton and the text messageshould be displayed on the form of the target application.

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 .NET

Symptoms
This article demonstrates how to create an Automation client for Microsoft Excel by using Microsoft Visual Basic .NET.
Resolution
Automation is a process that allows applications that are written in languages such as Visual Basic to programmatically control other applications. Automation to Excel allows you to perform actions such as creating a new workbook, adding data to the workbook, or creating charts. With Excel and other Microsoft Office applications, virtually all of the actions that you can perform manually through the user interface can also be performed programmatically by using Automation.
Excel exposes this programmatic functionality through an object model. The object model is a collection of classes and methods that serve as counterparts to the logical components of Excel. For example, there is an Application object, a Workbook object, and a Worksheet object, each of which contain the functionality of those components of Excel. To access the object model from Visual Basic .NET, you can set a project reference to the type library.
This article demonstrates how to set the proper project reference to the Excel type library for Visual Basic .NET and provides sample code to automate Excel. Create an 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. Form1 is created by default.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 Excel Object Library, and then click Select.
Note Microsoft Office 2003 includes Primary Interop Assemblies (PIAs). Microsoft Office XP does not include PIAs, but they can be downloaded. For more information about Office XP PIAs, click the following article number to view the article in the Microsoft Knowledge Base:
328912?(http://support.microsoft.com/kb/328912/) Microsoft Office XP primary interop assemblies (PIAs) are available for downloadClick OK in the Add References dialog box to accept your selections.On the View menu, select Toolbox to display the Toolbox, and then add a button to Form1.Double-click Button1. The code window for the form appears.In the code window, locate the following code:

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

Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.ClickDim oXL As Excel.ApplicationDim oWB As Excel.WorkbookDim oSheet As Excel.WorksheetDim oRng As Excel.Range’ Start Excel and get Application object.oXL = CreateObject(“Excel.Application”)oXL.Visible = True’ Get a new workbook.oWB = oXL.Workbooks.AddoSheet = 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 = Excel.XlVAlign.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).oRng = oSheet.Range(“C2″, “C6″)oRng.Formula = “=A2 & “” “” & B2″‘ Fill D2:D6 with a formula(=RAND()*100000) and apply format.oRng = oSheet.Range(“D2″, “D6″)oRng.Formula = “=RAND()*100000″oRng.NumberFormat = “$0.00″‘ AutoFit columns A:D.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 Excel’s lifetime.oXL.Visible = TrueoXL.UserControl = True’ Make sure that you release object references.oRng = NothingoSheet = NothingoWB = NothingoXL.Quit()oXL = NothingExit SubErr_Handler:MsgBox(Err.Description, vbCritical, “Error: ” & Err.Number)End SubPrivate Sub DisplayQuarterlySales(ByVal oWS As Excel.Worksheet)Dim oResizeRange As Excel.RangeDim oChart As Excel.ChartDim oSeries As Excel.SeriesDim 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 iNumQtrs’ Starting at E1, fill headers for the number of columns selected.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.oResizeRange = oWS.Range(“E2″, “E6″).Resize(ColumnSize:=iNumQtrs)oResizeRange.Formula = “=RAND()*100″oResizeRange.NumberFormat = “$0.00″‘ Apply borders to the Sales data and headers.oResizeRange = oWS.Range(“E1″, “E6″).Resize(ColumnSize:=iNumQtrs)oResizeRange.Borders.Weight = Excel.XlBorderWeight.xlThin’ Add a Totals formula for the sales data and apply a border.oResizeRange = oWS.Range(“E8″, “E8″).Resize(ColumnSize:=iNumQtrs)oResizeRange.Formula = “=SUM(E2:E6)”With oResizeRange.Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble.Weight = Excel.XlBorderWeight.xlThickEnd With’ Add a Chart for the selected data.oResizeRange = oWS.Range(“E2:E6″).Resize(ColumnSize:=iNumQtrs)oChart = oWS.Parent.Charts.AddWith oChart.ChartWizard(oResizeRange, Excel.XlChartType.xl3DColumn, , Excel.XlRowCol.xlColumns)oSeries = .SeriesCollection(1)oSeries.XValues = oWS.Range(“A2″, “A6″)For iRet = 1 To iNumQtrs.SeriesCollection(iRet).Name = “=”"Q” & Str(iRet) & “”"”Next iRet.Location(Excel.XlChartLocation.xlLocationAsObject, oWS.Name)End With’ Move the chart so as not to cover your data.With oWS.Shapes.Item(“Chart 1″).Top = oWS.Rows(10).Top.Left = oWS.Columns(2).LeftEnd With’ Free any references.oChart = NothingoResizeRange = NothingEnd Sub Add the following code to the top of Form1.vb:

Imports Microsoft.Office.Core Test the automation clientPress F5 to build and to run the program.On the form, click Button1. The program starts Excel and populates data on a new worksheet.When you are prompted to enter quarterly sales data, click Yes. A chart that is linked to quarterly data is added to the worksheet.

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.