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

How To Create a Basic Add-in Using VB5 or VB6

Symptoms
This article describes how to create the basic framework of an Add-in forVisual Basic 5.0 or 6.0. An Add-in utilizes the Visual Basic Extensibilityobject model to customize and extend the Visual Basic environment.
Resolution
In Visual Basic 5.0 or 6.0, you can create the code for a minimal Add-in project with a single step. You simply double-click on the Add-in icon when you start a new Visual Basic Project.
A Visual Basic 5.0 or 6.0 Add-in can be either an ActiveX DLL or ActiveXEXE, depending upon the project type setting in the Project Propertiesdialog.
By default, an ActiveX EXE is created by the Add-in Wizard for Visual Basic5.0 and an ActiveX DLL is created by default for Visual Basic 6.0. It isgiven the name MyAddin.vbp. In Visual Basic 5.0, three files are added tothis project, connect.cls, frmAddin.frm, and Addin.bas. The contents offiles are listed below with additional comments.
Visual Basic 5.0
Connect.cls

Option Explicit’The IDTExtensibility is used to gain access to the’necessary events in the extensibility model. These four’interface methods must be contained in this class’module and must contain at least one line of code. Even’if the line of code is a comment.”+ OnConnection’+ OnDisconnection’+ OnStartUpComplete’+ OnAddInsUpdate”Implements IDTExtensibility’FormDisplayed keeps track of whether your form is displayedPublic FormDisplayed As Boolean’VBInstance is used to identify which Visual Basic IDE the’Addin belongs to. Because you can have multiple’IDEs open, this identifies the correct IDE.Public VBInstance As VBIDE.VBE’mcbMenuCommandBar is a reference to the new menu item in the Addins’Menu.Dim mcbMenuCommandBar As Office.CommandBarControl’mfrmAddIn is used to reference the addins form.Dim mfrmAddIn As New frmAddIn’MenuHandler is the command bar event handler that gives’access to the command bar events that is used to notify the’addin that a menuitem was selected.Public WithEvents MenuHandler As CommandBarEvents’Hides the Addin Form’Sub Hide()On Error Resume NextFormDisplayed = FalsemfrmAddIn.HideEnd Sub’Shows the Addin Form’Sub Show()On Error Resume NextIf mfrmAddIn Is Nothing ThenSet mfrmAddIn = New frmAddInEnd If’Sets the forms Public VBInstance variable to the instance of Visual’Basic that the addin is being run under.Set mfrmAddIn.VBInstance = VBInstance’Sets the Forms Connect Variable to the instance of this class.Set mfrmAddIn.Connect = MeFormDisplayed = TruemfrmAddIn.ShowEnd Sub’This method adds the Add-In to VB.’Private Sub IDTExtensibility_OnConnection(ByVal VBInst As Object, _ByVal ConnectMode As vbext_ConnectMode, _ByVal AddInInst As VBIDE.AddIn, custom() As Variant)On Error GoTo error_handler’save the vb instanceSet VBInstance = VBInst’This is a good place to set a breakpoint and’test various addin objects, properties and methods.Debug.Print VBInst.FullNameIf ConnectMode = vbext_cm_External Then’Used by the wizard toolbar to start this wizard.Me.ShowElse’Create the Menu Item in the AddinMenu and’return a reference to it in mcbMenuCommandBar.’(See AddToAddInCommandBar function below.)’Set mcbMenuCommandBar = AddToAddInCommandBar(“My AddIn”)’Sets this Classes MenuHandler Event to receive events from the’Menu Item that was just added to the AddInCommandBar’(mcbMenuCommandBar).Set Me.MenuHandler = _VBInst.Events.CommandBarEvents(mcbMenuCommandBar)End If’ vbext_cm_AfterStartup indicates Addin is connected after IDE’ startup.’If ConnectMode = vbext_cm_AfterStartup Then’Checks in the Registry to see if it needs’to show the Addin when it connects.If GetSetting(App.Title, “Settings”, “DisplayOnConnect”, “0″) = _”1″ Then’Set this to display the form on connect.Me.ShowEnd IfEnd IfExit Suberror_handler:MsgBox Err.DescriptionEnd Sub’This method removes the Add-In from VB.’Private Sub IDTExtensibility_OnDisconnection(ByVal RemoveMode As _vbext_DisconnectMode, custom() As Variant)On Error Resume Next’Remove the Menu Item for the Add-inmcbMenuCommandBar.Delete’ Shut down the Add-In and Save the Visible state of the’ addin form for the next time the addin is loaded.’If FormDisplayed ThenSaveSetting App.Title, “Settings”, “DisplayOnConnect”, “1″FormDisplayed = FalseElseSaveSetting App.Title, “Settings”, “DisplayOnConnect”, “0″End IfUnload mfrmAddInSet mfrmAddIn = NothingEnd SubPrivate Sub IDTExtensibility_OnStartupComplete(custom() As Variant)If GetSetting(App.Title, “Settings”, “DisplayOnConnect”, “0″) = _”1″ Then’Set this to display the form on connect.Me.ShowEnd IfEnd Sub’As it has been mentioned above, all four interfaces must be’implemented and must contain at least one line of code for your add-in’to function properly. If you don’t have any particular code that you’want to put in these procedures, just insert a comment. If the’procedure is empty, it will be removed by the compiler.Private Sub IDTExtensibility_OnAddInsUpdate(custom() As Variant)’End Sub’This event fires when the menu is clicked in the IDE.Private Sub MenuHandler_Click(ByVal CommandBarControl As Object, _handled As Boolean, CancelDefault As Boolean)Me.ShowEnd SubFunction AddToAddInCommandBar(sCaption As String) As _Office.CommandBarControlDim cbMenuCommandBar As Office.CommandBarControl’command bar objectDim cbMenu As ObjectOn Error GoTo AddToAddInCommandBarErr’See if the Add-Ins menu can be found.Set cbMenu = VBInstance.CommandBars(“Add-Ins”)If cbMenu Is Nothing Then’Add-Ins menu is not available so you fail.Exit FunctionEnd If’Create a new menu item in the Add-Ins menu.’Set cbMenuCommandBar = cbMenu.Controls.Add(1)’Set the menu caption.’cbMenuCommandBar.Caption = sCaption’ Return a Reference to the New Menu Item.’Set AddToAddInCommandBar = cbMenuCommandBarExit FunctionAddToAddInCommandBarErr:End Function
frmAddin.frm

Public VBInstance As VBIDE.VBEPublic Connect As ConnectOption ExplicitPrivate Sub CancelButton_Click()’ Hide the Form’Connect.HideEnd SubPrivate Sub OKButton_Click()’ Place your specific Add-in code here’MsgBox “AddIn operation on: ” & VBInstance.FullNameEnd Sub
Addin.bas

Option ExplicitDeclare Function WritePrivateProfileString& Lib “Kernel32″ Alias”WritePrivateProfileStringA” (ByVal AppName$, ByVal KeyName$, _ByVal keydefault$, ByVal FileName$)’====================================================================’This sub should be executed from the Immediate window.’In order to get this app added to the VBADDIN.INI file,’you must change the name in the second argument to reflect’the correct name of your project.’====================================================================Sub AddToINI()Dim ErrCode As LongErrCode = WritePrivateProfileString(“Add-Ins32″,”MyAddIn.Connect”,”0″, “vbaddin.ini”)End Sub
Visual Basic 6.0Although the Add-in project code in Visual Basic 6.0 is very similar to theVisual Basic 5.0 code, only two files are added to the MyAddin project; thefrmAddin.frm and an ActiveX Designer (connect.dsr). The ActiveX Designer isan ActiveX component that has a programmable interface and a visualinterface. The Designer allows users to customize the Add-in for run-timeuse. The designer also contains the necessary AddinInstance Interface,rather than needing to implement the IDTExtensibility Interface.
On the General tab, the designer lets you customize some basic informationfor the Add-in such as the Display Name, Description, Host application andversion, Initial Load Behavior, and whether the Add-in contains a UserInterface.
On the Advanced tab, you have the option of selecting a Satellite DLL forLocalization and a Registry key to save additional Add-in specific data.
You can add code to the add-in through code by editing the designer codeand by adding code to frmAddin.
How to Run the Basic Add-in Using Visual Basic 5.0 or Visual Basic 6.0Start a new project and select the AddIn icon.If you are using Visual Basic 5.0, press CTRL+G to open the Immediate Window. Type addtoini, and press return.(NOTE: This step is not required in Visual Basic 6.0.)Press F5 to run the Add-In. This loads and registers the Add-In.Create a new Standard EXE in a second instance of Visual Basic.From the Add-Ins menu, select Add-in Manager.In Visual Basic 5.0, select the My Addin check box.
In Visual Basic 6.0, select My Add-In from the list, and select the Loaded/Unloaded check box. Click OK.From the Add-Ins menu, select My AddIn.Click OK to run your specific Add-In code in frmAddin. (A messagebox appears by default.) Click Cancel to close the form.

How To Compile VB Programs with Debug Symbols Embedded

Symptoms
The “Compile to Native Code” option introduced in Visual Basic versions 5.0 and 6.0 not only improves performance of Visual Basic programs and components, but also makes it possible to debug them with the Visual C++ debugger.
This article shows you how to compile a Visual Basic program or componentwith embedded debug symbols. By doing so, you simplify the debuggingprocess and avoid the problems associated with mismatched and improperlyplaced symbols.
Resolution
All it takes to compile a Visual Basic program or component with embeddeddebug symbols is a properly set environment variable, LINK. The key is toset it in such a way that Visual Basic inherits the setting when it islaunched. To do this, follow the steps below:
There are several ways to set the LINK environment variable, each of thesemethods is outlined below:
Windows NT or Windows 95/98/MeOpen an MS-DOS Prompt.Navigate to the folder containing Visual Basic.Execute the following command, “set link=/pdb:none” without quotes.Start Visual Basic from the MS-DOS command prompt.
Windows NT OnlyFrom the Control Panel, select the System icon.Select the Environment tab.In the Variable entry, enter “link” without quotes.In the Value entry, enter the following:
/pdb:nonePress Set, then Apply.Start Visual Basic from the MS-DOS command prompt.
Windows 95/98/Me OnlyMake a backup copy of the AutoExec.Bat file.Open the Autoexec.bat file with Notepad.Exe or any text editor.Add the following entry to the AutoExec.Bat file:
set link=/pdb:noneSave the AutoExec.Bat file.Execute the AutoExec.Bat file or reboot the machine.Start Visual Basic.
Once the LINK environment variable is set, a Visual Basic project can becompiled with embedded debug symbols. The following steps describe howto create a test program and compile it with embedded debug symbols:
Step-by-Step ExampleCreate a new Standard EXE project in Visual Basic. Form1 is created bydefault.Add a CommandButton (Command1) to Form1.Add the following code to Form1:

Private Sub Command1_Click()Dim s As Strings = App.EXENamePrint sEnd Sub Select Project1 Properties from the Project menu.Select the Compile tab.Select Compile to Native Code, check Create Symbolic Debug Info, andselect No Optimization.Save the project and create Project1.EXE. Note that the EXE is createdwith embedded debug symbols.

How To Associate a Custom Icon with a Formless Visual Basic Application

Symptoms
For Visual Basic applications that do not contain forms, you can still provide a custom icon for the executable. This article explains how you can add an icon resource to the project.
Resolution
When you create a Visual Basic executable application, you can select an icon from one of the project’s forms in the Icon drop-down list box on the Make tab of the Project Properties dialog box to use as the icon for the executable file. However, if there are no forms in the project, no icons are available in the drop-down list box of the Make tab. In this case, you can create a custom icon resource in your project. The compiler uses this resource as the icon for your executable file. If you include more than one icon, the compiler uses the icon whose letter appears first in the alphabet because it prioritizes alphabetically.
The following sample demonstrates how to provide a custom icon for a simple, formless Visual Basic EXE project. For this sample, you may select an icon from your system, or you can create your own. By default, Visual Basic 6.0 installs icons in the following folder:
C:\Program Files\Microsoft Visual Studio\Common\Graphics\Icons\ To create your own icon, you can use a tool such as Image Editor, which is available from the Visual Basic 6.0 CD (Disk 1) or the Visual Studio 6.0 CD (Disk 3) at the following location:
\Common\Tools\VB\Imagedit\Imagedit.exe
Step-by-Step ExampleCreate a new Visual Basic standard EXE project. Form1 is created by default.Right-click Form1 in the Project window, and then click Remove Form1 to remove the form from the project.Add a new standard module (Module1) to the project.Paste the following code into the code window of Module1:

Public Sub Main()MsgBox “Hello World”End Sub Select an icon from the list, or use Image Editor (or another appropriate tool) to create an icon file.To load the Visual Basic Resource Editor, follow these steps:From the Add-Ins menu, click Add-In Manager.Locate VB 6 Resource Editor in the list of available add-ins.Double-click VB 6 Resource Editor to load the editor add-in.From the Tools menu, click Resource Editor.In the Resource Editor window, click Add Icon on the toolbar. (This button appears as a small gray square that is outlined in blue.)Open the icon file that you created earlier.By default, the icon is added with the name “101″. Right-click the icon resource that was just added, and then click Properties.In the Id box, type APPICON to rename the icon resource, and then click OK.
NOTE: “APPICON” is just a suggested name for your resource. If you already have other, named icon resources, make sure that your executable icon begins with a letter that occurs later in the alphabet than the other icons. For example, if you have an icon that is named “AAA” and another that is named “BBB”, the compiler uses the one that is named “AAA” as your application icon.From the File menu, click Make to compile the Visual Basic project.In Windows Explorer, browse to the location where you compiled your executable file. Notice that the icon for the executable file is the icon that you selected in the Resource Editor.

BUG: Data Form Wizard Through Application Wizard Omits ADO Reference

Symptoms
When you run an application that is created using the Visual Basic Application Wizard, you receive the following error message:

Compile error: User-defined type not defined
Resolution
The Application Wizard allows for the creation of forms via the Data FormWizard. When a form is created in this manner, a reference to ADO is notadded to the project.

“Differences Between Visual Basic .NET and Visual C# .NET” white paper is available

Symptoms
This article points to the “Differences Between Microsoft Visual Basic .NET and Microsoft Visual C# .NET” white paper.
Resolution
Because of the previous differences between Visual Basic and C/C++, many developers assume incorrectly about the capabilities of Visual Basic .NET. Many Visual Basic developers think that Visual C# is a more powerful language than Visual Basic. In other words, Visual Basic developers assume that you can do many things in Visual C# that you cannot do in Visual Basic .NET, just as there are many things that you can do in C/C++ but cannot do in Microsoft Visual Basic 6.0 or earlier. This assumption is incorrect.
Although there are differences between Visual Basic .NET and Visual C# .NET, both are first-class programming languages that are based on the Microsoft .NET Framework, and they are equally powerful. Visual Basic .NET is a true object-oriented programming language that includes new and improved features such as inheritance, polymorphism, interfaces, and overloading. Both Visual Basic .NET and Visual C# .NET use the common language runtime. There are almost no performance issues between Visual Basic .NET and Visual C# .NET. Visual C# .NET may have a few more “power” features such as handling unmanaged code, and Visual Basic .NET may be skewed a little toward ease of use by providing features such as late binding. However, the differences between Visual Basic .NET and Visual C# .NET are very small compared to what they were in earlier versions.
The “Differences Between Microsoft Visual Basic .NET and Microsoft Visual C# .NET” white paper describes some of the differences between Visual Basic .NET and Visual C# .NET. However, remember that the .NET Framework is intended to be language independent. When you must select between Visual Basic .NET and Visual C# .NET, decide primarily based on what you already know and what you are comfortable with. It is easier for Visual Basic 6.0 developers to use Visual Basic .NET and for C++/Java programmers to use Visual C# .NET. The existing experience of a programmer far outweighs the small differences between the two languages.
No matter which language you select based on your personal preference and past experience, both languages are powerful developer tools and first-class programming languages that share the common language runtime in the .NET Framework.
The following file is available for download from the Microsoft Download Center:

Collapse this imageExpand this image
Download the “Differences between Microsoft Visual Basic .NET and Microsoft Visual C# .NET” white paper package now.(http://download.microsoft.com/download/6/3/5/6354bf47-c597-4029-89e9-2495e7539ab9/vbcsharpwp.exe)Release Date: June 18, 2002
For more information about how to download Microsoft Support files, click the following article number to view the article in the Microsoft Knowledge Base:
119591?(http://support.microsoft.com/kb/119591/)How to obtain Microsoft support files from online servicesMicrosoft scanned this file for viruses. Microsoft used the most current virus-detection software that was available on the date that the file was posted. The file is stored on security-enhanced servers that help prevent any unauthorized changes to the file.

PRB: Run-Time Error 713 Opening Data Report in Distributed Application

Symptoms
You are distributing a Visual Basic application that includes a data report. After installation, you receive the following error when you attempt to open the data report from your application:

Run-time error ‘713′:Application-defined or object defined error
Resolution
The Data Report run-time file (Msdbrptr.dll) was not included in your setup package.