Introduction
This is a VB6 tutorial which helps beginners to update their VB6 skills.
Background
All of us know that Visual Basic 6 is the simplest way to develop Windows application for desktop computer. In this special tip, we are going to learn a code poem which automatically clears the text box content with few lines of code. The idea sounds good, isn't it?
Using the Code
Firstly, let's make a Sub
to clear the fields. I have two methods, the first one lets you clear selected text box which utilizes the paramArray
argument and the second will clear the entire field in a form.
Open your Visual Basic 6.0 and enter the following sub routine.
Sub ClearBox for Selected Boxes
Sub ClearBox (ParamArray boxes() As Variant)
Dim ct As Variant
For Each ct In boxes
If TypeOf ct Is TextBox Then
ct.Text = ""
End If
Next
End Sub
This sub
will clear the passed textbox
controls on the form. The sub
utilizes the paramArray
feature, so that the program can accept any number of arguments/controls. Remember that paramArray
object should be a type of variant.
Clear All the Boxes
The second method will clear all the boxes on the form. Let's take a look at the second code.
Sub ClearBox_Auto(f As Form)
Dim ob As Object
Dim ct As Control
For Each ob In Form1.Controls
Set ct = ob
If TypeOf ct Is TextBox Then
ct.Text = ""
End If
Next
End Sub
Form's controls property is returning the object collection and we collect each of then to 'ob
' and then assign to a control variable and then can do the similar type of operations done in Clear Box sub
.
Auto Number Format 'Sub'
Finally, I have a special format box which utilises Forms controls collection to gather controls appeared in the User Interface and apply specific number format to all the number field as follows:
Sub AutoNumberFormat(f As Form)
Dim ob As Object
Dim ct As Control
For Each ob In Form1.Controls
Set ct = ob
If TypeOf ct Is TextBox Then
If IsNumeric(ct.Text) Then
ct.Text = Format(ct, "0.00")
End If
End If
Next
End Sub
Call the Box Function
Let's invoke the subroutines on the click event of command button:
Call ClearBox(TextBox1, TextBox2, TextBox3)
Call ClearBox_Auto(Me)
Call AutoNumberFormat(Me)
Note
The code is working on Microsoft Word VBA and Visual Studio 6.0 alike. For using on Word VBA, please replace the Form (in argument) with UserForm
.
Points of Interest
I found this tricky code, when I was trying to format Text Boxes in our project, we have more than 10 forms and each has many boxes and it becomes full of repetitive codes and I simply re-write it with this idea and it saves my time and space.
History
I will keep looking for code poems and many ideas are rolling out of my head. Keep kooling on my blog Code Poetry for more.