Visual Basic Classic

163K

Solutions

58K

Contributors

Visual Basic is Microsoft’s event-driven programming language and integrated development environment (IDE) for its Component Object Model (COM) programming model. It is relatively easy to learn and use because of its graphical development features and BASIC heritage. It has been replaced with VB.NET, and is very similar to VBA (Visual Basic for Applications), the programming language for the Microsoft Office product line.

Share tech news, updates, or what's on your mind.

Sign up to Post

This article describes how to use a set of graphical playing cards to create a Draw Poker game in Excel or VB6.
2
 
LVL 25

Expert Comment

by:Shums
Comment Utility
Great Expert with great mind
0
 
LVL 48

Author Comment

by:Martin Liss
Comment Utility
Thanks.
0
Ready to get started with anonymous questions?
LVL 9
Ready to get started with anonymous questions?

It's easy! Check out this step-by-step guide for asking an anonymous question on Experts Exchange.

If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
1
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
2
 
LVL 66

Expert Comment

by:Jim Horn
Comment Utility
If you could add a paragraph painting a picture of what you just said then we'll be good.
0
 
LVL 66

Expert Comment

by:Jim Horn
Comment Utility
Nicely written.  I'm currently in an Oracle shop that has a wompload of .xml, .sql, and Java files that are used to build a monster data warehouse where using a tool like this is very important for supporting code.  

Voted Yes.
0
Eggs in one array
You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes a way to elegantly solve the problem.
6
 
LVL 1

Expert Comment

by:sdeller
Comment Utility
The suggestion using UBound is incorrect.  With the code like this:
  CustData(UBound(CustData)).strCustName = ...
  CustData(UBound(CustData)).dblSales = ...
the code will create a new entry with the first assignment, causing UBound to increment. So the second line will refer to yet another new entry.  You need to assign both values with one assignment.
0
 
LVL 48

Author Comment

by:Martin Liss
Comment Utility
I'm sorry but that is not correct. In VB6, once an array is created the only ways to increase the upper bound of the array is through Dim, Redim and Redim Preserve. If you place this bit of code in a new project you'll see that I'm correct.

Option Explicit

Private Type CustomerData
    strCustName As String
    dblSales As Double
End Type
Private Sub Form_Load()
Dim CustData() As CustomerData
Dim lngIndex As Long

ReDim CustData(2)

CustData(0).dblSales = 0
CustData(0).strCustName = "Customer 0"

CustData(1).dblSales = 100
CustData(1).strCustName = "Customer 1"

MsgBox "The upper bound of CustData is " & UBound(CustData)

CustData(UBound(CustData)).dblSales = 200
CustData(UBound(CustData)).strCustName = "Customer 2"

MsgBox "The upper bound of CustData is still " & UBound(CustData)

For lngIndex = 0 To UBound(CustData)
    Debug.Print CustData(lngIndex).strCustName & " has sales of " & CustData(lngIndex).dblSales
Next
End Sub

Open in new window

0
Oh no
This article describes some techniques which will make your VBA or Visual Basic Classic code easier to understand and maintain, whether by you, your replacement, or another Experts-Exchange expert.
68
 

Expert Comment

by:M Melson
Comment Utility
Very nice article. Thank you for taking the time writing and sharing it.  I can use part with variable names to indicate the type of variable. Good advice.
0
 
LVL 48

Author Comment

by:Martin Liss
Comment Utility
Thanks.
0
Example PowerPoint Add-In
I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
5
 
LVL 16

Expert Comment

by:Kyle Santos
Comment Utility
Great job!
0
 
LVL 12

Author Comment

by:Jamie Garroch
Comment Utility
Thanks Kyle Santos :-)
0
Background
What I'm presenting in this article is the result of 2 conditions in my work area:
  1. We have a SQL Server production environment but no development or test environment; and
  2. We have an MS Access front end using tables in SQL Server but we are not using any other components of SQL Server (i.e., we are not utilizing stored procedures, views, table-valued functions, etc.).
Without these 2 conditions, I would not present this article as a possible work around.  Even without the second condition, if you have a development or test environment, I would recommend using those environments instead of what is presented in the article.  Also, I acknowledge that there may be several other alternatives to what I'm presenting but recognize that's usually the case with any challenge we face.

Why Develop this VBA
I have created a MS Access database front end using SQL Server as the backend for data storage only.  Although eventually I'd like to run all my processes through stored procedures in SQL Server so that the front end platform could be changed, the volume of data is small enough to run my processes through MS Access VBA.  Also, my experience with SQL Server is progressing but not to the point of being able to quickly write the code in the time needed to complete this project.  So, I'll come back to writing the code later.

We issue the MS Access front end to members of our team through an …
0

Introduction

I frequently answer questions where strings need to be 'cleaned' of multiple space characters. The most common fix is to remove leading or trailing spaces. For that problem, there are very handy intrinsic VB functions (LTrim, RTrim, Trim). However, these functions do not affect any repeated space characters between the first and last non-space characters -- the internal spaces.
 
In this article, I will explore different solutions to this problem and evaluate their performance. You should be able to apply this in any of the Office products (Access, Excel, PowerPoint, Word), VBScript, or VB6. However, the collection object is not available in the VBScript environment, so you won't be able to use or test any of the methods that use the collection object in your VBS batch jobs.
 
Note: You can use these methods to remove any repeating characters inside a string, not just repeated space characters.
 

Problem Context

You often have little say in the data you must process. Count yourself lucky if you get well-formed, normalized, and structured data. However, if you receive any of the following, this article may help you.

  • unstructured data (text files) that you will need to parse or format
  • text or memo (varchar) database fields with raw data
  • HTML or XML that may look good in a browser, but isn't easy to parse or format
  • XML or JSON (any tagged data format) that you need to compact before sending or saving
 

Performance Methodologies

6

Introduction

On a recent question, I supplied a simple function to format a number with a suffix, denoting its scale (MB, GB, TB, etc.).  While the function was simple enough, I wondered if I had supplied the most efficient code.  This article compares the performance of the Array() and Split() functions.


The Problem

The question (http:Q_28494315.html) stated a need to add the scale suffix to a number.  Excel did not provide the ability to format cell values this way and conditional formatting does not affect the cell's value.  The cell still contains a numeric value, while Excel displays the formatted value.


Example:


123456 = 123.456 KB
12345600 = 12.3456 MB
1234560000 = 1.23456 GB


The Accepted and Alternative Solutions

Since there were only three possible suffixes, the conditional formatting solution was the simplest and the one accepted as the question solution.

[>999999999999]0.00,,,,"TB";[>999999999]0.00,,,"GB";0.00,,"MB"

Open in new window

Starting with Excel 2007, it is possible to use the conditional formatting wizard (see below) to create a conditional formats with more than three conditions.  I am writing a separate article on this.
ConditionalFormattingRulesMgr.jpg


The User-Defined Function Solutions

Let's start with a routine that uses an Array() function, most closely resembling the question's solution.  If the magnitude of the parameter value is greater than 1000, we use the base1000 log of the number to index into the Array() values.


SizeA -- An Array() function



Open in new window

1

Introduction

I recently answered a question where the solution involved creating files with numeric names in particular ranges (in this case, 1 to 23 and 30).  This article shows how to implement a range iterator for your VBA/VBScript/VB projects.


Our Goal

When you finish reading the article, I want you to understand the different solution paths and be able to implement them in your projects.  The desired code is

  • simple
  • efficient
  • easy to understand
  • easy to maintain
 

The Brute Force approach

For expediency, I used a brute force solution in answering the question.  In the following example, assume that the Debug.Print line represents the actual task that needs to be accomplished for that numeric value.

Sub LoopingRanges_BruteForce()
    Dim lngLoop As Long
    For lngLoop = 1 To 23
        Debug.Print lngLoop, ;
    Next
    For lngLoop = 30 To 30
        Debug.Print lngLoop, ;
    Next
    Debug.Print
End Sub

Open in new window


Expected Output

For the non-parameterized code examples, their output will be the following sequence in the Immediate window.

1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  30           

Open in new window


The Arrays Function

There is a very handy function with which you can create one-dimensional (vectors) and multi-dimension arrays (2D, 3D, ...60D).  We can use the Array() function to create a vector (1D array) of two item lists (also vectors).  Each of the two item lists will be the lower and upper bounds for our loop.  Our BruteForce example now transforms into this streamlined routine.


Open in new window

2
 
LVL 46

Author Comment

by:aikimark
Comment Utility
In case you need to support decreasing ranges as well as increasing ranges:
Sub testRR()
    Dim lngLoop As Long
    Dim vItem As Variant
    Dim lngStep As Long
    
    For Each vItem In ReturnRanges_Arrays("5..1,11,28..30,19..15")
        
        lngStep = Sgn(vItem(1) - vItem(0))
        If lngStep = 0 Then lngStep = 1
        
        For lngLoop = vItem(0) To vItem(1) Step lngStep
            Debug.Print lngLoop, ;
        Next
    Next
    Debug.Print
End Sub

Open in new window

0
 
LVL 54

Expert Comment

by:Joe Winograd, EE MVE 2015&2016
Comment Utility
Nice addition!
0
[Webinar] How Hackers Steal Your Credentials
LVL 9
[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Hi,

xyPainter - It is a generic Add-In useful for anybody working extensively on PowerPoint and Excel.

For PowerPoint - xyPainterForPPT.pptx
For Excel - xyPainterForXLS.pptx

Preface
More often we find ourselves in a situation “Why didn't Microsoft” think of it, after all it is so simple and obvious. But as a Programmer the one fact I have come to realize is “there are lots on everybody¿s plate and very less time to furnish it”, whilst Microsoft is busy fixing the critical bugs, thanks to all the MVP¿s[I am not One :(, Grrr] and other Open Source themed Programmers[I am trying to be One :), Kudos] for taking their time out and developing all those free utilities which so often save our time whenever
we hit a wall in one of our Projects.

About
“xyPainter” is one of many free Add-Ins you find around the web dedicated to make people¿s life far easier. The idea came to me when I exhaustively googled[obviously] for such an Add-In and could not find one[at least on the first 4 Pages - :) LOL]. “xyPainter” assists to paint the Size and/or Position of one
object to another[Hmmm more like “Format Painter”] only a bit multitasking.

Features
• Object Independent i.e., You can read the data from one type of object[Ex : Table] and apply to a different type of object[Ex: Image]
• Unlike “Format Painter” it is not a toggle switch, “Format Painter” remains active only for one application whereas “xyPaint” and “sizePaint” can be applied as many …
1
 
LVL 1

Author Comment

by:Ravi N
Comment Utility
Hi Michael,

Thanks for your detailed instructions, it really helped. I have edited my article based on your suggestions.

Please review and let me know if it is fine.

Regards,
Ravi N
0
 
LVL 101

Expert Comment

by:mlmcc
Comment Utility
You have made a better attempt but the article is supposed to stand on its own and not rely on the attachments for the actual details.

You need to put the text and code from the PowerPoints into the article.  If you feel it is better, the code can be attached to facilitate the user in downloading it all at once rather than having to copy short snippets.

mlmcc
Page Editor
0

Introduction

While training and mentoring a new user with a Microsoft Access application I'd written for the client, a quite unexpected condition occurred in my application. This would normally be the kind of condition that prompts me to find an error I'd introduced and not trapped. However, this time the error elicited exclamations of wonder and puzzlement. Surely this could not happen... but I was a witness and couldn't deny my own eyes.

Accepting the possibility that it could happen and creating a do-over (with different key) patch was my highest priority. That patch allowed the application to continue with that day's production run. Disaster had been averted and I left the client's office shaking my head in disbelief. Time to put on my Computer Scientist cap. This is the story of my research and a warning or alert to all VB developers who use the PRNG features of the VB language.

PRNG is not a new Visual Basic statement, feature, referenced class, nor a new kind of potato chip. It is an acronym for Pseudo-Random Number Generator. I'll get to the details about PRNGs and VB PRNG features in a moment. Firstly, I should explain why a Microsoft Access business application needs to use PRNG features.

The Application

Several years ago, we added a feature to this executive survey application that allows the survey taker to answer the survey questions online through their Internet browser. Originally, the surveys were all paper answers that were typed…
2
 
LVL 46

Author Comment

by:aikimark
Comment Utility
While writing the follow-up article, I noticed that the Application Source Figure 2 string literal is missing an "H" character.

The correct assignment to have all 62 alphanumeric characters should be:
    strCharBase = "01234ABCDEFGHIJKLMNOPQRSTUVWXYZ" & _
        "abcdefghijklmnopqrstuvwxyz56789"

Open in new window

0
When changes need to be made to code, the easiest thing to do is obviously to just add, change or delete lines and be done with it. The problem with that is that after making several modifications you may find that you need to undo something you did and it may be difficult to remember what changes were made. It can also be difficult to remember why and/or when you made the changes.

I learned by experience that the easy method is not the best method and so I started annotating my changes like the following...

where this is the original code
 
    gbQuit = True
    frmProject.lblCounting.Caption = "Quit command accepted..."
    frmProject.tbarProject.Buttons(3).Enabled = False
    mnuPrint.Enabled = False

Open in new window


and this is the modified code.
 
    
    gbQuit = True
    'new
    frmProject.lblCounting.Caption = "Quit command accepted..."
    'frmProject.tbarProject.Buttons(3).Enabled = False
    frmProject.tbarProject.Buttons(4).Enabled = False

    mnuPrint.Enabled = False

Open in new window


That would indicate to me that I changed the line that refers to the 'Buttons' and showed me what is was before, and the blank line indicated that the change ended on the line above it. That's all well and good but it doesn't help resolve the why and when issue.

My annotation scheme now includes two ingredients.

Part 1.
I add a module named ChangeLog to every project. The contents of ChangeLog always look something like the following. For …
15
 

Expert Comment

by:Kelvin4
Comment Utility
Hi Martin
I wish I'd found this earlier, its great - thanks.
I confirm that the dll worked first time in Visio 2013. When I opened the app, the toolbar was in place, and it worked as in excel.

However, I wish I had taken more notice of your guidance: "Note that while this is a COM add-in you won't see it listed if you go to either File|Options|Add-Ins|COM Add-Ins (or Excel Add-ins)." Then I'd not have spent time searching for it in the visio Trust Centre!

One suggestion,
I tend to add date and time to my my annotations (DDMMYYYY hh:mm, ).  I realise you have this in the Change Log, but sometimes I find it helpful to have the date & time in situ in the code.

Could 'Set descriptive text' button cause to add Date & Time  between 'START' and the trailing '*****' template text?

Thanks
Kelvin
0
 
LVL 48

Author Comment

by:Martin Liss
Comment Utility
You can enter anything you like manually but if you are asking if it could automatically reflect the current date and time there's no provision for doing that. If you want to discuss this further please use the "Ask a Question" button that you'll find at the bottom of the article or send me a normal EE message.
0
Applications concerned with document scanning and archiving, and other automatic file generation software, can produce large numbers of files with primitive names allocated at runtime. These names can be based on such primitive identifiers as time and date stamp information only, which may not be sufficiently descriptive of the files' contents or general type to be of much use in subsequently identifying their relevance. In such cases, the files may benefit from being renamed categorically. So for example, say we have 1000 files containing photographs of automobile parts, the original names of these files could be changed from those relatively unhelpful datestamps, to names reflective of what they actually contain.

This VB programme relieves the tedium of having to do that job on large numbers of files manually. The user is presented with a template into which any combination of alphanumeric filename characters can be entered. Each character in the filename template can have its dynamics controlled, meaning that there is a choice at individual character level, as to whether to make the new character in a given position fixed, or incrementable.

This allows a bunch of files to retain a kind of root identifier in part of their name, so that they can all be instantly recognised as belonging to the same group, but at the same time other characters in the filenames can be made dynamic, so that they run through the alphabet, or cycle through numbers 0-9. You can even adjust …
2
 
LVL 16

Author Comment

by:krakatoa
Comment Utility
ericpete - that's fine and great, and thanks for the files prompt - I agree entirely with what you said. ;)
0
 
LVL 15

Administrative Comment

by:Eric AKA Netminder
Comment Utility
krakatoa,

Your article has been designated EE-Approved. Very nicely done!

ericpete
Page Editor
0
There is often more than one way to accomplish a particular coding task and one of the criteria that can be used to determine which method to use is to determine which one is the fastest.  But how do you do that? You could try using displays of Visual Basic's Now() or Time() functions, and doing that will get you some results but they won't be very accurate since the accuracy of those functions is only about 1 second and that is huge compared to the time it takes to run a line, or even in most cases, thousands of lines of code. To improve on that you'll need to use an API. Some of the API possibilities are GetTickCount, TimeGetTime and QueryPerformanceCounter. Here's a chart of the commonly used methods and their accuracy.

Accuracy
As you can see, GetTickCount and TimeGetTime are a hundred times more accurate than the VB functions and 10 ms is likely fine enough for any code that you want to time. QueryPerformanceCounter is much more accurate than that in that it can measure actual CPU cycles but most programmers will never need to do that.

Here's a VB6 example that uses GetTickCount. In this case a comparison is done between 'Test1' where the Array function to fill an array, and 'Test2' where a more manual approach is used.  

Each test uses a loop that repeats an action the same, large, number of times. The use of the large number of loops magnifies the results of the test and that is necessary because an individual line of code can be almost too fast…
12
 
LVL 56

Expert Comment

by:Bill Prew
Comment Utility
How about using Timer() in VBS?

~bp
0
 
LVL 48

Author Comment

by:Martin Liss
Comment Utility
I can't say one way or the other for VBA since my main experience is with VB6 but Microsoft says the resolution of the Timer function is just 1 second.
0
What Started It All
I had an instance recently where I needed to take text from a textbox on a VBA form and split the text into separate lines to send to a zebra printer.  The catch was that I needed the text to break at the same line points as the VBA textbox.  The textbox was configured with multiline and wordwrap enabled.  Searching all over the internet for a function or idea to accomplish this task, I found plenty of examples of wrapping text based on already included carriage returns or just of a space and character count, but not what I needed.  A VBA textbox may or may not have carriage returns and it splits text on more than just spaces.  

This led me on a quest to build a word wrap function mimicking the wrapping of a textbox.  Working through coding and testing, I ended up creating a few different versions.  The earlier versions were better than what I had found, but not good enough for my needs.  They are posted here in case they are good enough for you.  The original function returned data in a string array, but it was easy to adjust it to return as single string with carriage returns to break apart each line.  That code is also included.

Breakdown of the basic code:
A textbox has a variety of rules on how it separates text.  The first step is to take the text and split it into an array based on already defined line feeds.  Use the line feed (vbLf) as this will catch user entered returns from both Enter Key (If EnterKeyBehavior = True) and …
3
 
LVL 61

Expert Comment

by:mbizup
Comment Utility
Voted 'Yes' above.
0
Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.
 

What are they?

An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains a list of valid elements. Here’s an example:

Private Enum MyEnum ‘  May also be Public
    FirstElement
    SecondElement
    ThirdElement
    FourthElement
    ‘etc.
End Enum      

You would place that code in the Declarations section (in other words at the top) of any type of form or module. Each value in the list is defined internally by VB as a Long Integer and by default the first element will be given a value of 0, the second a value of 1, and so on.

You might be saying to yourself that you could do that with constants like this

Private Const FirstElement = 0
Private Const SecondElement = 1
Private Const ThirdElement = 2
Private Const FourthElement = 3

and you'd be right, but there are several advantages to Enums that will become apparent as you read on. Two that I’ll mention now however are: they are faster and take up less memory than strings and Intellisense will be available when you use them as shown in this picture. If you’ve forgotten how to invoke Intellisense, you press Ctrl+Spacebar, and in this case it was done after the equal sign was entered.

Using Intellisense to show Enum values
You may not have realized it but you’ve probably run into Enums which are built into Visual Basic.

The built-in days of the week Enum
10
 

Expert Comment

by:isnoend2001
Comment Utility
Thanks i have some code to use this
0
 

Expert Comment

by:Esot
Comment Utility
Good clarification, thanks
0
When designing a form there are several BorderStyles to choose from, all of which can be classified as either 'Fixed' or 'Sizable' and I'd guess that 'Fixed Single' or one of the other fixed types is the most popular choice. I assume it's the most popular because when you choose a sizable border style the controls on the form don't resize when the user resizes the form and that's pretty ugly, and in my opinion makes sizable forms useless in most situations.

The CResizer class that is embedded here  CResizer.cls  solves that problem. Since CResizer is a class you can implement it in any of your applications in two simple steps:

1.    Add the CResizer class to your project
2.    Add  the following in any form where you want the form's controls to dynamically move and resize when the form is resized.

 
Option Explicit
Private clsResize As CResizer

Private Sub Form_Resize()
    clsResize.ResizeControls Me
End Sub

Private Sub Form_Load()

    Set clsResize = New CResizer
    clsResize.Initialize Me
    
 End Sub

Open in new window


Once you have done that, every control on the form will be both resized and moved when the form is resized. There may be occasions however where you don't want certain controls to be moved and/or you don't want them resized and/or you want the control's font to be adjusted, and so the class gives you control over how individual controls are handled by way of five parameters.
 
Parameter 1: The control's name

Parameter 2: Move? True/False, with True as the default

Parameter 3: Resize? True/False, with True as the default

Parameter 4: Adjust Font Size? True/False, with False as the default

5
 
LVL 48

Author Comment

by:Martin Liss
Comment Utility
Nice work Brook. I've updated the class.
0
 
LVL 48

Author Comment

by:Martin Liss
Comment Utility
Added new functionality to the class. See Parameter 5.
0
Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone to do so.

The attached control is a modified TextBox does all that for you and it also has these additional properties:

CanHaveDecimals - This is a Boolean property that determines if the number can have decimals or not

CanBeNegative - This is a Boolean property that determines if the number can be negative or not

MaxDecimals - This property allows the user to set the maximum allowable number of decimals

MinValue - This property allows the user to set the minimum acceptable value

MaxValue - This property allows the user to set the maximum acceptable value

DecimalSeparator - This property determines which character ("." or ",") is used as the decimal separator

RequireLeadingDigit - This is a Boolean property that determines if at least one digit must preceed the decimal separator

Here is a link to the code which once compiled will add the NumberBox to the list of available project Components. You can add the control to a project by going to Project|Components and checking NumberBox. I would have liked to be able to attach the code here in a zip file, but the zip contains file types that Experts Excgange …
2
Industry Leaders: We Want Your Opinion!
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't interested in and/or not all of the procedures that led up to arriving at the break point. Adding Debug.Print statements or MsgBox statements in procedures is another way but adding them manually can be very tedious. The add-in I've attached resolves those problems by automatically adding  statements in all selected procedures that contains "Debug.Print" or whatever else you want along with the name of the procedure. 
When the add-in is loaded this toolbar will be added to the Visual Basic IDE in VB6 or the VBE (Visual Basic Environment) in Excel.
Insert-Procedure-Names-Toolbar.jpgThe button on the right in the toolbar is the one that you use to set the prefix value and when it is clicked this window is displayed.
Choose-Code.jpgThe default for the prefix string is "Debug.Print" but you can choose "Const Proc_Name = " or set the prefix to anything else you want including "Msgbox" by choosing 'Other' and entering the value. Note that the 'Const PROC_NAME' prefix can be very valuable if you want to be able to include procedure names in your error routines.
And this shows the VB6 version of the window that appears if you click the first button in the toolbar. You use it to select the procedures to be modified. (The VBA …
3
 
LVL 48

Author Comment

by:Martin Liss
Comment Utility
Updated 9/3/2014
Version 3.0 - Many bug fixes and performance-improving changes including:
New toolbar and selection icons
Corrected a problem where the WARNING line could be added more than once to the same procedure
Corrected a problem where objects added after the 'Select Procedures' was shown for the first time weren't being included
Previous selections are now remembered each time 'Select Procedures' is shown
Added a second button to the addin toolbar as a replacement for the InputBox that used to be used, so that the user isn't repeatedly asked what marker he wants to use
0
 
LVL 48

Author Comment

by:Martin Liss
Comment Utility
Updated 9/20/2014
Version 3.0.1

Corrected bug where commented out procedures were being considered as active code.
0
Here are a few simple, working, games that you can use as-is or as the basis for your own games.

Tic-Tac-Toe
This is one of the simplest of all games.
 Tic-Tac-Toe.zip

The game allows for a choice of who goes first and keeps track of the number of wins for each person. Here is a picture of the game in action.
 Two-Player game in actionThe following is a variation of the game that allows you to play against the computer (which can't be beaten).
 Tic-Tac-Toe-VS-CPU.zip

Hangman
Hangman is also a simple game but depending on the word you need to solve, it can be challenging. The words used are in a file called SecretWords.txt and it's included in the zip file. You can of course add to or delete words in the list.
 Hangman.zip

Here's a picture of the game in progress where the player is trying to solve the word 'elephant' and has incorrectly tried 'F'.
 Hangman in progressBlackjack
The 3rd and last game is blackjack which you can download from
here.

The programming for this game is more complex than the other two and here is what the game looks like.
 BlackjackThe game allows you to place a bet of any size up to the limit of your bankroll (which it shows you) and after you start the hand it gives you the chance to 'Hit', 'Stick', 'Double Down' (not shown). While the hand is in progress the game keeps track of your hand count (which in this case is 20) following the …
4
 
LVL 48

Author Comment

by:Martin Liss
Comment Utility
The "malware" may have been the ocx that contains the cards so here is one that should work.

To use the zip:
  1. Download it
  2. Right click on the file
  3. Choose "Extract All" or whatever shows up in your Windows OS
  4. After extraction, double-click on the VBP file

If you have any further problems please send me an EE message.
BJ-no-ocx.zip
1
 
LVL 11

Expert Comment

by:Andrew Leniart
Comment Utility
Many thanks Martin. Appreciate it! :)
0
Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Assert which when used in a line of code like Debug.Assert MyBoolean will cause a break in the program at that line if MyBoolean is True. Both Debug statements will be ignored when the program is compiled so they are superior to MsgBox statements which need to be removed before a program is compiled, unless, of course, you want the user to know the value of MyVar.

Debug statements are useful but limited However there is another debugging method that is less well known and that is conditional compilation. Conditional compilation uses special #!f, #Else, #ElseIf and #End If reserved words that like Debug are not included in compiled code. This can be very handy in debugging where you can do something like

 
#If MyVar > 5 Then ' or the value of some Boolean is True, etc.
    ' Do something (or any number of things)
#Else 
    ' Do something else
#End If

Open in new window


I find it particularly useful when doing things like that to set up a 'Conditional Compilation Argument' by going to Project|<MyProgramName|Properties|Make and putting something like Testing = -1 in the  'Conditional Compilation Arguments:'  box. Note that -1 or any non-zero value equates to True and that Conditional Compilation arguments have global scope. In other words they are available anyplace in your program.  Once I've done that I can do something like the following which is code from one of my apps.

 

Open in new window

7
If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that follows allows you to easily do just that.

A few things to note about the code.

o Microsoft Word must be installed on your PC and on any of your users' PCs in order for this code to work
o No Reference to Word is required in your application
o The code as shown will check spelling but you can also have it check grammar by changing the objDoc.CheckSpelling line  to objDoc.CheckGrammar
o You can replace the textbox with a RichTextbox if you like and the code will work with it as well
o In Excel you will need to remove the App.OleRequestPendingTimeout = 999999 line
o The code expects an ActiveX textbox named "Text1" and an ActiveX command button named "SpellCheck"

 
Private Sub SpellCheck_Click()

    Dim objWord As Object
    Dim objDoc  As Object
    Dim strResult As String
    Const QUOTE = """"
    
    On Error GoTo ErrorRoutine

    App.OleRequestPendingTimeout = 999999
    Set objWord = GetObject("Word.Application")
    If TypeName(objWord) <> "Nothing" Then
        ' Word is already open
        Set objWord = GetObject(, "Word.Application")
    Else
        ' Create an instance of Word
        Set objWord = CreateObject("Word.Application")
    End If

    Select Case objWord.version
 

Open in new window

4
The debugging module of the VB 6 IDE can be accessed by way of the Debug menu item. That menu item can normally be found in the IDE's main menu line as shown in this picture.

 Debug Menu ItemThere is also a companion Debug Toolbar that looks like the following and that toolbar will be the focus of this tutorial:

 Debug ToolbarIf you can't find that toolbar then you can add it to the menus by pulling down the View menu item, clicking Toolbars, and checking Debug.

Components of the Debug Toolbar
They are (in order)
o Continue (toggle)
o Break
o End
o Toggle Breakpoint
o Step Into
o Step Over
o Step Out
o Locals Window
o Immediate Window
o Watch Window
o Quick Watch
o Call Stack

The following is an explanation of what each button does. (I've changed the order a bit.)

Start/Continue (toggle)
Availability: Design time and when in break mode
Shortcut: F5

Clicking Start not surprisingly starts your program running just likes F5 does. After Start is clicked it is disabled.

Break
Availability: Run time only
Shortcut: CTRL+BREAK

Once your program has started, and, for example, the main form has loaded and it is ready for interaction with the user, pressing the Break button pauses the execution of the program and takes you to the edit window for the form. Pressing the button also has the effect of enabling the Start button and toggling it to Continue. At this point you can do things like adding or changing …
24
 

Expert Comment

by:LD16
Comment Utility
Very useful and helpful article!
0
 

Expert Comment

by:Sonny Day
Comment Utility
A very useful tutorial - thanks a million.. I was familiar with several of the commands per se, but not with the toolbars and the windows. This will simplify the task of debugging a great deal!
1

Introduction

While answering a recent question about filtering a custom class collection, I realized that this could be accomplished with very little code by using the ScriptControl (SC) library.  This article will introduce you to the SC library and apply it to collection filtering.  We will show you how to incorporate this into your classes.
http://www.experts-exchange.com/Q_27419023.html

Note: It is also possible to create an ADO recordset and populate it with your class properties.  You could then use the recordset's filtering capabilities to identify which items meet the filter criteria.

The ScriptControl library

For those of you who have used the Eval(Access) or Evaluate(Excel) functions, you are invoking a scripting engine.  You can use the SC library to add run-time scripting to your code.  This library allows your VB/VBA/VB.Net code to create and execute VB.Script code.

Common ScriptControl Uses
Without having to write very much code, you can add the following functionality to your compiled applications with the SC library.
Macro capabilities -- user-supplied code at run time
Calculator function -- on-the-fly math expressions

The best way to think about the SC is that it is a little VB 'engine' that runs the statements you supply it.  You can supply a single line or many routines.  The control follows the same syntax rules you would encounter in the VB classic …
5

Visual Basic Classic

163K

Solutions

58K

Contributors

Visual Basic is Microsoft’s event-driven programming language and integrated development environment (IDE) for its Component Object Model (COM) programming model. It is relatively easy to learn and use because of its graphical development features and BASIC heritage. It has been replaced with VB.NET, and is very similar to VBA (Visual Basic for Applications), the programming language for the Microsoft Office product line.