VBA Excel Assigning an universal condition to textboxes

666 views Asked by At

So I have a userform with a set of textboxes. In general I am taking their inputs and printing to a textfile.

User Screen:

UserScreen

Current Output:

output

So I have code that prints the three values in a line in a txt file. Box1.Value + Box2.Value + Box3.Value etc.

The issue is when the user DOESN'T enter anything. Based on how this text file is read either the correct code OR just something like spaces or null equivalent to the max length of the text box.

Current Code:

If Len(Box1.Value) < Box1.MaxLength Then
Box1.Value = Space(Box1.MaxLength)
End If

Desired Output:

goodoutput

Now what if I want this to work for ALL TEXT BOXES. If a bad entry (less than the desired length) or no entry - then all textboxes occupy their max length. This would really help standardize the userform and save a lot of lines of code. (currently have 15 different text boxes).

Is there something like this in VBA? Can I put all the textboxes in an array in VBA?

----------------------------------After Tim's Answer----------------------------

Test Case

Test

Test Code

Dim UserEntry As String


Private Sub Check_Click()

If Len(TestBox.Value) < TestBox.MaxLength Then
TestBox.Value = Space(TestBox.MaxLength)
End If

UserEntry = TestBox.Value
TestCase.TestCaseLabel.Caption = UserEntry
End Sub
Private Sub Export_Click()

Dim myFile As String
myFile = "C:\Reformatted.txt"
Open myFile For Output As #1

If Len(TestBox.Value) < TestBox.MaxLength Then
TestBox.Value = Space(TestBox.MaxLength)
End If

UserEntry = TestBox.Value
Print #1, UserEntry

Close #1
Shell "C:\Windows\Notepad.exe C:\Reformatted.txt", 1
End Sub

Function ValueIfMaxLength(tb As TextBox) As String

    ValueIfMaxLength = IIf(tb.Value = tb.MaxLength, tb.Value, Space(tb.MaxLength))

End Function
1

There are 1 answers

6
Tim Williams On BEST ANSWER

You should be able to use a function to simplify your code. Something like:

Function ValueOrDefault(tb as msforms.Textbox) As String
                     'assumed padding with spaces on right...
    ValueOrDefault = Left(tb.Value & Space(tb.MaxLength), tb.MaxLength)

End Function

EDIT: If only "maxlength" values are valid...

Function ValueIfMaxLength(tb as msforms.Textbox) As String

    ValueIfMaxLength = IIf(Len(tb.Value) = tb.MaxLength, _
                           tb.Value, Space(tb.MaxLength))
    ''uncomment the next line if you want the textbox content to be updated
    'tb.Value = ValueIfMaxLength

End Function

Example usage:

Private Sub Export_Click()

    Const myFile As String = "C:\Reformatted.txt"

    Open myFile For Output As #1
    Print #1, ValueIfMaxLength(TestBox)
    Close #1
    Shell "C:\Windows\Notepad.exe " & myFile, 1

End Sub