Load event isn't working. Visual Basic - forms

I'm trying to write a lottery application and have written out all the code. Everything seems to be fine except the part where it's supposed to show the winning numbers and the user's numbers. When the ResultsForm pops up, all the labels are blank instead of having the numbers filled in. Any help would be greatly appreciated. I will include the code for the MainForm, the ResultsForm and the Module I used.
Public Class MainForm
Dim rand As New Random
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
GenerateNewLotteryNumbers()
End Sub
Private Sub btnCheckNumbers_Click(sender As Object, e As EventArgs) Handles btnCheckNumbers.Click
If ValidateUserPicks() Then
DisplayResults()
End If
End Sub
Private Sub btnPlayAgain_Click(sender As Object, e As EventArgs) Handles btnPlayAgain.Click
GenerateNewLotteryNumbers()
Reset()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Sub GenerateNewLotteryNumbers()
For intCount = 0 To g_intUPPER_SUB
g_intNumbers(intCount) = rand.Next(10)
Next
End Sub
Sub Reset()
txtDigit1.Clear()
txtDigit2.Clear()
txtDigit3.Clear()
txtDigit4.Clear()
txtDigit5.Clear()
txtDigit1.Focus()
End Sub
Sub DisplayResults()
Dim frmResults As New ResultsForm
frmResults.ShowDialog()
End Sub
Function ValidateUserPicks() As Boolean
Dim blnIsValid As Boolean = False
If Integer.TryParse(txtDigit1.Text, g_intUserPicks(0)) And
g_intUserPicks(0) >= 0 And g_intUserPicks(0) <= 9 Then
If Integer.TryParse(txtDigit2.Text, g_intUserPicks(1)) And
g_intUserPicks(1) >= 0 And g_intUserPicks(1) <= 9 Then
If Integer.TryParse(txtDigit3.Text, g_intUserPicks(2)) And
g_intUserPicks(2) >= 0 And g_intUserPicks(2) <= 9 Then
If Integer.TryParse(txtDigit4.Text, g_intUserPicks(3)) And
g_intUserPicks(3) >= 0 And g_intUserPicks(3) <= 9 Then
If Integer.TryParse(txtDigit5.Text, g_intUserPicks(4)) And
g_intUserPicks(4) >= 0 And g_intUserPicks(4) <= 9 Then
End If
blnIsValid = True
Else
MessageBox.Show("Digit 5: Enter a number between 0 and 9.")
txtDigit5.Focus()
txtDigit5.SelectAll()
End If
Else
MessageBox.Show("Digit 4: Enter a number between 0 and 9.")
txtDigit4.Focus()
txtDigit5.SelectAll()
End If
Else
MessageBox.Show("Digit 3: Enter a number between 0 and 9.")
txtDigit3.Focus()
txtDigit3.SelectAll()
End If
Else
MessageBox.Show("Digit 2: Enter a number between 0 and 9.")
txtDigit2.Focus()
txtDigit2.SelectAll()
End If
Return blnIsValid
End Function
End Class
ResultsForm:
Public Class ResultsForm
Private Sub ResultsForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
DisplayLotteryNumbers()
ShowResults()
End Sub
Private Sub btnOk_Click(sender As Object, e As EventArgs) Handles btnOk.Click
Me.Close()
End Sub
Sub DisplayLotteryNumbers()
lblWinningNumber1.Text = g_intNumbers(0).ToString
lblWinningNumber2.Text = g_intNumbers(1).ToString
lblWinningNumber3.Text = g_intNumbers(2).ToString
lblWinningNumber4.Text = g_intNumbers(3).ToString
lblWinningNumber5.Text = g_intNumbers(4).ToString
lblYourNumber1.Text = g_intNumbers(0).ToString
lblYourNumber2.Text = g_intNumbers(1).ToString
lblYourNumber3.Text = g_intNumbers(2).ToString
lblYourNumber4.Text = g_intNumbers(3).ToString
lblYourNumber5.Text = g_intNumbers(4).ToString
End Sub
Sub DisplayWinnerForm()
Dim frmWinner As New WinnerForm
frmWinner.ShowDialog()
End Sub
Sub ShowResults()
Select Case MatchingDigits()
Case 1
lblResults.Text = "One Matching Digit."
Case 2
lblResults.Text = "Two Matching Digits."
Case 3
lblResults.Text = "Three Matching Digits."
Case 4
lblResults.Text = "Four Matching Digits."
Case 5
lblResults.Text = "All Digits Match!"
DisplayWinnerForm()
Case Else
lblResults.Text = "No Matching Digits."
End Select
End Sub
Function MatchingDigits() As Integer
Dim numMatches As Integer
For intCount = 0 To g_intUPPER_SUB
If g_intNumbers(intCount) = g_intUserPicks(intCount) Then
numMatches += 1
End If
Next
Return numMatches
End Function
End Class
Module:
Module LotteryModule
Public Const g_intUPPER_SUB As Integer = 4
Public g_intNumbers(g_intUPPER_SUB) As Integer
Public g_intUserPicks(g_intUPPER_SUB) As Integer
End Module

Related

simplest Unostructure that supports he getByName

In LibreOffice Basic sub I use a bunch of uno properties in an array. Which is the simplest Unostructure or UnoService that I must "embed" them, in order to use the getByName "function"?
Example:
dim props(1) as new com.sun.star.beans.PropertyValue
props(0).Name = "blahblah1"
props(0).Value = "blahblah1Value"
props(1).Name = "blahblah2"
props(1).Name = 3000
I want to be able to use something like:
b = props.getByName("blahblah2").Value
or something like (assuming I "assigned" them in a structure-like-object called "somestruct") :
b = somestruct.getprops.getByName("blahblah2").Value
As I understand that this can be done by creating a "UnoService" which supports the getByName and then, somehow, assigning these props to this service
Which is the "lightest" such service?
(I mean the service that uses less resources)
Thanks in advance.
Really supporting the interface XNameAccess is not as easy. The services which implement this interface are supposed using this interface for existing named properties, not for own created ones.
But you can use the service EnumerableMap to achieve what you probably want.
Example:
sub testEnumerableMap
serviceEnumerableMap = com.sun.star.container.EnumerableMap
oEnumerableMap = serviceEnumerableMap.create("string", "any")
oEnumerableMap.put("blahblah1", "blahblah1Value")
oEnumerableMap.put("blahblah2", 3000)
oEnumerableMap.put("blahblah3", 1234.67)
msgbox oEnumerableMap.get("blahblah1")
msgbox oEnumerableMap.get("blahblah2")
msgbox oEnumerableMap.get("blahblah3")
'msgbox oEnumerableMap.get("blahblah4") 'will throw error
msgbox oEnumerableMap.containsKey("blahblah2")
msgbox oEnumerableMap.containsValue(3000)
if oEnumerableMap.containsKey("blahblah4") then
msgbox oEnumerableMap.get("blahblah4")
end if
end sub
But starbasic with option Compatible is also able supporting Class programming like VBA does.
Example:
Create a module named myPropertySet. Therein put the following code:
option Compatible
option ClassModule
private aPropertyValues() as com.sun.star.beans.PropertyValue
public sub setProperty(oProp as com.sun.star.beans.PropertyValue)
bUpdated = false
for each oPropPresent in aPropertyValues
if oPropPresent.Name = oProp.Name then
oPropPresent.Value = oProp.Value
bUpdated = true
exit for
end if
next
if not bUpdated then
iIndex = ubound(aPropertyValues) + 1
redim preserve aPropertyValues(iIndex)
aPropertyValues(iIndex) = oProp
end if
end sub
public function getPropertyValue(sName as string) as variant
getPropertyValue = "N/A"
for each oProp in aPropertyValues
if oProp.Name = sName then
getPropertyValue = oProp.Value
exit for
end if
next
end function
Then within a standard module:
sub testClass
oPropertySet = new myPropertySet
dim prop as new com.sun.star.beans.PropertyValue
prop.Name = "blahblah1"
prop.Value = "blahblah1Value"
oPropertySet.setProperty(prop)
prop.Name = "blahblah2"
prop.Value = 3000
oPropertySet.setProperty(prop)
prop.Name = "blahblah3"
prop.Value = 1234.56
oPropertySet.setProperty(prop)
prop.Name = "blahblah2"
prop.Value = 8888
oPropertySet.setProperty(prop)
msgbox oPropertySet.getPropertyValue("blahblah1")
msgbox oPropertySet.getPropertyValue("blahblah2")
msgbox oPropertySet.getPropertyValue("blahblah3")
msgbox oPropertySet.getPropertyValue("blahblah4")
end sub
LibreOffice Basic supports the vb6 Collection type.
Dim coll As New Collection
coll.Add("blahblah1Value", "blahblah1")
coll.Add(3000, "blahblah2")
MsgBox(coll("blahblah1"))
Arrays of property values are the only thing that will work for certain UNO interfaces such as dispatcher calls. If you simply need a better way to deal with arrays of property values, then use a helper function.
Sub DisplayMyPropertyValue
Dim props(0 To 1) As New com.sun.star.beans.PropertyValue
props(0).Name = "blahblah1"
props(0).Value = "blahblah1Value"
props(1).Name = "blahblah2"
props(1).Name = 3000
MsgBox(GetPropertyByName(props, "blahblah1"))
End Sub
Function GetPropertyByName(props As Array, propname As String)
For Each prop In props
If prop.Name = propname Then
GetPropertyByName = prop.Value
Exit Function
End If
Next
GetPropertyByName = ""
End Function
XNameAccess is used for UNO containers such as Calc sheets. Normally these containers are obtained from the UNO interface, not created.
oSheet = ThisComponent.Sheets.getByName("Sheet1")
May UNO objects support the XPropertySet interface. Normally these are also obtained from the UNO interface, not created.
paraStyleName = cellcursor.getPropertyValue("ParaStyleName")
It may be possible to create a new class in Java that implements XPropertySet. However, Basic uses helper functions instead of class methods.
I think the serviceEnumerableMap is the answer (so far). Creating the values and searching them was much faster then creating props in a dynamic array and searching them with a for loop in basic.
(I do not "dare" to use "option Compatible", although I was a big fun of VB6 and VBA, because of the problems in code that maybe arise).
I used this code to test time in a form:
SUB testlala(Event)
TESTPROPS(Event)
' TESTENUM(Event)
MSGBOX "END OF TEST"
END SUB
SUB TESTENUM(Event)
DIM xcounter AS LONG
'b = now()
serviceEnumerableMap = com.sun.star.container.EnumerableMap
oEnumerableMap = serviceEnumerableMap.create("string", "any")
FOR xcounter= 0 TO 10000
oEnumerableMap.put("pr" & FORMAT(xcounter,"0000"), xcounter -10000)
NEXT
'b=now()-b
b = now()
FOR xcounter = 1 TO 5000
lala = Int((9000 * Rnd) +1)
g =oEnumerableMap.get("pr" & FORMAT(lala,"0000"))
'MSGBOX GetValueFromName(props,"pr" & FORMAT(xcounter,"0000"))
NEXT
b=now()-b
MSGBOX b*100000
END SUB
SUB TESTPROPS(Event)
DIM props()
DIM xcounter AS LONG
'b = now()
FOR xcounter= 0 TO 10000
AppendProperty(props,"pr" & FORMAT(xcounter,"0000"), xcounter -10000)
NEXT
'b=now()-b
b = now()
FOR xcounter = 1 TO 5000
lala = Int((9000 * Rnd) +1)
g = GetValueFromName(props,"pr" & FORMAT(lala,"0000"))
'MSGBOX GetValueFromName(props,"pr" & FORMAT(xcounter,"0000"))
NEXT
b=now()-b
MSGBOX b*100000
END SUB
REM FROM Andrew Pitonyak's OpenOffice Macro Information ------------------
Sub AppendToArray(oData(), ByVal x)
Dim iUB As Integer 'The upper bound of the array.
Dim iLB As Integer 'The lower bound of the array.
iUB = UBound(oData()) + 1
iLB = LBound(oData())
ReDim Preserve oData(iLB To iUB)
oData(iUB) = x
End Sub
Function CreateProperty(sName$, oValue) As com.sun.star.beans.PropertyValue
Dim oProperty As New com.sun.star.beans.PropertyValue
oProperty.Name = sName
oProperty.Value = oValue
CreateProperty() = oProperty
End Function
Sub AppendProperty(oProperties(), sName As String, ByVal oValue)
AppendToArray(oProperties(), CreateProperty(sName, oValue))
End Sub

How to capture images automatically in basic4android

Hello I am creating an application in which camera captures images automatically at a interval of 1 second. In below code I can take images on button click. But I want auto-camera.
Here is the code. Please help me how can I create?
Sub Process_Global
End Sub
Sub Globals
Dim camera1 As Camera
Dim btnTakePicture As Button
Dim Panel1 As Panel
End Sub
Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("1")
End Sub
Sub Camera1_Ready (Success As Boolean)
If Success Then
camera1.StartPreview
btnTakePicture.Enabled = True
Else
ToastMessageShow("Cannot open camera.", True)
End If
End Sub
Sub Activity_Resume
btnTakePicture.Enabled = False
camera1.Initialize(Panel1, "Camera1")
End Sub
Sub Activity_Pause (UserClosed As Boolean)
camera1.Release
End Sub
Sub Camera1_PictureTaken (Data() As Byte)
camera1.StartPreview
Dim t As Long
Dim filename As String
t = DateTime.Add(DateTime.Now,0,0,1)
filename = t & ".jpg"
Dim out As OutputStream
out = File.OpenOutput(File.DirRootExternal, filename, False)
out.WriteBytes(Data, 0, Data.Length)
out.Close
ToastMessageShow("Image Saved" , True)
btnTakePicture.Enabled = True
End Sub
Sub btnTakePicture_Click
btnTakePicture.Enabled = False
camera1.TakePicture
End Sub

Link Variable to Label on another form in vb

I have a small program for some college coursework, i have to enter data of the gender and age of a group of people then work out the male and female percent and the child and adult percent. The bit i am stuck with is i want to display my results on labels on a separate form. Here is my code:
Public Class Form1
Dim TotalGender As Integer
Dim TotalAge As Integer
Dim MaleCount As Integer
Dim FemaleCount As Integer
Dim ChildCount As Integer
Dim AdultCount As Integer
Dim MalePercent As Single
Dim FemalePercent As Single
Dim AdultPercent As Single
Dim ChildPercent As Single
Private Sub btnSub_Click(sender As Object, e As EventArgs) Handles btnSub.Click
If cmbGender.Text = "Male" Then
MaleCount += 1
End If
If cmbGender.Text = "Female" Then
FemaleCount += 1
End If
If cmbAge.Text > 18 Then
ChildCount += 1
End If
If cmbAge.Text <= 18 Then
AdultCount += 1
End If
End Sub
Private Sub btnResults_Click(sender As Object, e As EventArgs) Handles btnResults.Click
Form2.Show()
MalePercent = MaleCount / TotalGender * 100
FemalePercent = FemaleCount / TotalGender * 100
AdultPercent = AdultCount / TotalAge * 100
ChildPercent = ChildCount / TotalAge * 100
End Sub
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
TotalGender = 0
TotalAge = 0
MaleCount = 0
FemaleCount = 0
ChildCount = 0
AdultCount = 0
MalePercent = 0
FemalePercent = 0
AdultPercent = 0
ChildPercent = 0
End Sub
End Class
My second form has all the labels already placed and i know how to display results on a label, i just don't know how to transfer the results across to another form
You can write on form 1 .It shows your results on form2
Form2.Label1.Text = AdultCount
Form2.Show()

Passing classes variables in vba

I know there is a way to pass class variables in vb.net as such:
Module Module1
Sub Main()
' Declare an instance of the class and assign a value to its field.
***Dim c1 As Class1 = New Class1()***
c1.Field = 5
Console.WriteLine(c1.Field)
' Output: 5
' ByVal does not prevent changing the value of a field or property.
ChangeFieldValue(***c1***)
Console.WriteLine(***c1.Field***)
' Output: 500
' ByVal does prevent changing the value of c1 itself.
ChangeClassReference(c1)
Console.WriteLine(c1.Field)
' Output: 500
Console.ReadKey()
End Sub
Public Sub ChangeFieldValue(***ByVal cls As Class1***)
cls.Field = 500
End Sub
Public Sub ChangeClassReference(***ByVal cls As Class1***)
cls = New Class1()
cls.Field = 1000
End Sub
Public Class Class1
Public Field As Integer
End Class
End Module
However when I try to emulate the same procedure in vba, it doesn't work.
is it possible to do in vba (for Excel)?
Try the following.
Sub Main()
Dim c1 As New Class1
c1.Field = 5
Debug.Print c1.Field
changeFieldValue c1
Debug.Print c1.Field
changeClassReference c1
Debug.Print c1.Field
End Sub
Public Sub changeClassReference(cls As Class1)
Set cls = New Class1
cls.Field = 1000
End Sub
Public Sub changeFieldValue(cls As Class1)
cls.Field = 500
End Sub
You'll need to add a new class module with the following code:
Public Field As Long

Restrict what someone types in a textbox

Here's what I want to do and I have a problem.
I want to restrict what an user types in certain textboxes. I want to leave him type only numbers but after 3 numbers to add a ";". (eg. 007;123;003;005;).
The problem is that my textbox Controls are generated through a bunch of code. So I can't or I don't know how to set an action to these controls.
The code I'm using to generate the controls is:
Set cControl = form.Controls("io" & masina).Add(
"Forms.Label.1", "lreper" & l & pagina, True)
With cControl
.Caption = "Reper"
.Width = 35
.Height = 9
.Top = 25 + k
.Left = 5
End With
Any ideas?
Thanks a lot!
You can use the key press event to restrict only numbers and the ";". Along with check conditions.
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
'// Numbers 0-9
Case 48 To 57
If Len(TextBox1.Text) = 3 And Right(TextBox1.Text, 3) Like "###" Then
KeyAscii = 0
GoTo DisplayFormatError
End If
'// Key ;
Case 59
If Len(TextBox1.Text) < 3 Or Not Right(TextBox1.Text, 3) Like "###" Then
KeyAscii = 0
GoTo DisplayFormatError
End If
Case Else
KeyAscii = 0
GoTo DisplayFormatError
End Select
Exit Sub
DisplayFormatError:
MsgBox "Please enter serial number in the format '000;000;000'", vbInformation, "Alert!"
End Sub
A better way would be to use a regular expression instead of the like method.
If you need help adding the events for your controls at runtime have a look at:
Add controls and events to form at runtime
EDIT (REQUEST BY TIAGO)
Dynamic creation of Userform and Textbox with keypress event. Uses modified example of above link. Credit to original author.
Add reference - Under Available References, click "Microsoft Visual Basic for Applications Extensibility" and click OK.
Option Explicit
Sub MakeForm()
Dim TempForm As Object ' VBComponent
Dim FormName As String
Dim NewTextBox As MSForms.TextBox
Dim TextLocation As Integer
Dim TextBoxName As String
'** Additional variable
Dim X As Integer
'Locks Excel spreadsheet and speeds up form processing
Application.VBE.MainWindow.Visible = False
Application.ScreenUpdating = False
'Create the UserForm
Set TempForm = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm)
'Set Properties for TempForm
With TempForm
.Properties("Caption") = "Temporary Form"
.Properties("Width") = 200
.Properties("Height") = 100
End With
FormName = TempForm.Name
TextBoxName = "MyTextBox"
'Add a CommandButton
Set NewTextBox = TempForm.Designer.Controls _
.Add("Forms.TextBox.1")
With NewTextBox
.Name = TextBoxName
.Left = 60
.Top = 40
End With
'Add an event-hander sub for the CommandButton
With TempForm.CodeModule
'** Add/change next 5 lines
'This code adds the commands/event handlers to the form
X = .CountOfLines
.InsertLines X + 1, "Private Sub " & TextBoxName & "_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)"
.InsertLines X + 2, "KeyAscii = KeyPress(" & TextBoxName & ".Text, KeyAscii)"
.InsertLines X + 3, "End Sub"
End With
'Show the form
VBA.UserForms.Add(FormName).Show
'Delete the form
ThisWorkbook.VBProject.VBComponents.Remove VBComponent:=TempForm
End Sub
Public Function KeyPress(ByVal strText As String, ByVal KeyAscii As Integer) As Integer
Select Case KeyAscii
'// Numbers 0-9
Case 48 To 57
If Len(strText) = 3 And Right(strText, 3) Like "###" Then
GoTo DisplayFormatError
End If
'// Key ;
Case 59
If Len(strText) < 3 Or Not Right(strText, 3) Like "###" Then
GoTo DisplayFormatError
End If
Case Else
GoTo DisplayFormatError
End Select
KeyPress = KeyAscii
Exit Function
DisplayFormatError:
KeyPress = 0
MsgBox "Please enter serial number in the format '000;000;000'", vbInformation, "Alert!"
End Function
ANOTHER METHOD (Using an event handler class)
Code in Userform:
Private colEventHandlers As Collection
Private Sub UserForm_Initialize()
'// New collection of events
Set colEventHandlers = New Collection
'// Add dynamic textbox
Set tbxNewTextbox = Me.Controls.Add("Forms.TextBox.1", "MyNewTextbox", True)
With tbxNewTextbox
.Top = 25
.Left = 5
End With
'// Add the event handler
Dim objEventHandler As TextboxEventHandler
Set objEventHandler = New TextboxEventHandler
Set objEventHandler.TextBox = tbxNewTextbox
colEventHandlers.Add objEventHandler
End Sub
And add a class module and rename it too "TextBoxEventHandler", then add the following code:
Private WithEvents tbxWithEvent As MSForms.TextBox
Public Property Set TextBox(ByVal oTextBox As MSForms.TextBox)
Set tbxWithEvent = oTextBox
End Property
Private Sub tbxWithEvent_Change()
End Sub
Private Sub tbxWithEvent_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
'// Numbers 0-9
Case 48 To 57
If Len(tbxWithEvent.Text) = 3 And Right(tbxWithEvent.Text, 3) Like "###" Then
GoTo DisplayFormatError
End If
'// Key ;
Case 59
If Len(tbxWithEvent.Text) < 3 Or Not Right(tbxWithEvent.Text, 3) Like "###" Then
GoTo DisplayFormatError
End If
Case Else
GoTo DisplayFormatError
End Select
Exit Sub
DisplayFormatError:
KeyAscii = 0
MsgBox "Please enter serial number in the format '000;000;000'", vbInformation, "Alert!"
End Sub
Try Dataannotations / metadata
More here: http://msdn.microsoft.com/en-us/library/ee256141.aspx
AFAIK and if i understood well, there is no way to handle this before user input.
Yet, you can use the TextBox_Exit event to format it afterwards. You can adapt this sample of code.
Although I'd never use dynamic controls unless strictly required, I got puzzled by this question... so I'm thinking of it as a challenge. :-)
Googled around and most answers falls into the same solution, however most of them comes with a 'I couldn't make it work' comment as well, including this one here in SO Assign on-click VBA function to a dynamically created button on Excel Userform.
Here's the code I built... which obviously does not work, otherwise I'd say it could be a solution. The problem on it is that the keypress method it creates dynamically is not called when should be. To test it, just paste the code into a VBA form named 'myForm'.
I kept the TextBox1_KeyPress only for testing purposes, to prove the usability of the text field validator (I'm sorry #Readfidy, your code didn't work for me as expected. I was able to add more than 3 numbers in a row).
In case anyone else is interested in making this code works... I'd be happy to thank ;-)
Option Explicit
Private Sub UserForm_Activate()
Dim sTextBoxName As String
Dim cControl As MSForms.TextBox
Dim sMetaFunction As String
Dim CodeModule
sTextBoxName = "lreper"
Set cControl = myForm.Controls.Add("Forms.TextBox.1", sTextBoxName, True)
With cControl
.Top = 25
.Left = 5
End With
sMetaFunction = "Private Sub " & sTextBoxName & "_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)" & vbCrLf & _
vbCrLf & _
vbTab & "Set KeyAscii = EvaluateText(myForm.Controls(" & sTextBoxName & "), KeyAscii)" & vbCrLf & _
vbCrLf & _
"End Sub"
Set CodeModule = ActiveWorkbook.VBProject.VBComponents.VBE.ActiveCodePane.CodeModule
CodeModule.InsertLines 60, sMetaFunction
End Sub
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Set KeyAscii = EvaluateText(myForm.Controls("TextBox1"), KeyAscii)
End Sub
Private Function EvaluateText(ByRef oTextBox As MSForms.TextBox, ByVal KeyAscii As MSForms.ReturnInteger) As MSForms.ReturnInteger
If ((Len(oTextBox.Text) + 1) / 4 = CInt((Len(oTextBox.Text) + 1) / 4)) Then
If KeyAscii <> 59 Then KeyAscii = 0
Else
If KeyAscii < 48 Or KeyAscii > 57 Then KeyAscii = 0
End If
If KeyAscii = 0 Then
MsgBox "Please enter serial number in the format '000;000;000'", vbInformation, "Alert!"
End If
End Function
USE THIS CODE : NO CLASS NEEDED !
USERFORM CODE
Private Function QNumber(ByRef oTextBox As MSForms.TextBox, ByVal KeyAscii As MSForms.ReturnInteger) As MSForms.ReturnInteger
On Error Resume Next
Select Case KeyAscii
Case 45 '"-"
If InStr(1, oTextBox.Text, "-") > 0 Or oTextBox.SelStart > 0 Then
KeyAscii = 0
End If
Case 46 '"."
If InStr(1, oTextBox.Text, ".") > 0 Then
KeyAscii = 0
End If
Case 48 To 57 '0-9"
Case Else
KeyAscii = 0
End Select
End Function
TEXTBOX CODE
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Set KeyAscii = QNumber(Me.Controls("TextBox1"), KeyAscii)
End Sub