VBA Excel 为文本框分配通用条件

VBA Excel Assigning an universal condition to textboxes

所以我有一个带有一组文本框的用户表单。一般来说,我会接受他们的输入并打印到文本文件中。

用户屏幕:

当前输出:

所以我有代码在 txt 文件的一行中打印这三个值。 Box1.Value + Box2.Value + Box3.Value 等等

问题是用户没有输入任何内容。根据此文本文件的读取方式,可以是正确的代码,也可以是空格之类的东西,也可以是相当于文本框最大长度的空值。

当前代码:

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

期望输出:

现在,如果我希望它适用于 所有文本框,该怎么办?如果条目错误(小于所需长度)或没有条目 - 那么所有文本框都会占用其最大长度。这确实有助于标准化用户表单并节省大量代码行。 (目前有 15 个不同的文本框)。

VBA里有这样的东西吗?我可以将所有 文本框放入数组 中 VBA 吗?

--------------------------------蒂姆回答后-------- --------------------

测试用例

测试码

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

您应该能够使用函数来简化您的代码。 类似于:

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

编辑:如果只有 "maxlength" 个值有效...

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

用法示例:

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