Excel、VBA、文本框:根据 ID 号对文本部分进行排序?

问题描述 投票:0回答:1

我对该页面和 Excel vba 代码都很陌生。因此,我在工作中遇到问题,我很乐意获得帮助。 我有以下问题。在我的 UserForm9 中,我有很多用于向 Excel 单元格输入数据的文本框。表单中有一个文本框,二维码数据被扫描到其中。代码格式为“P1000 3214”、“P1220 3101”等。始终是 Pxxxx_xxxx。

Printscreen of Userform

我正在尝试做的事情如下: 当二维码被扫描到文本框1时,自动将最后4个数字复制到与“P”和前4个数字(P1000)关联的另一个文本框中。在我的情况下,“P”和前4个数字是成分的标识符,应该链接到文本框(例如:P1000 链接到 Textbox2 和 Textbox3(如果 textbox2 已满)。

我有大约 30 个这样的标识符(P1000、P1500),所以我不知道是否可以用一个通用代码编写它,或者是否需要一次又一次地为每个标识符编写。

我无法通过 Google 找到答案,所以你是我解决该问题的最后机会。

如果你们能帮助我,非常感谢。

西蒙

excel vba textbox
1个回答
0
投票

如果您以“P”代码命名文本框,可能有比这更好的解决方案,但假设它们被命名为“Tb1”、“Tb2”等,然后尝试这个...代码必须位于用户表单。代码注释了以便您理解。

Private Sub Tb1_Change()
    Dim sText As String
    sText = UCase(Tb1.Text) ' in case of lowercase 'p' ... if required?
    ' validate contents of the TextBox are as expected
    If Len(sText) = 10 Then
        If Mid$(sText, 1, 1) = "P" And Mid$(sText, 6, 1) = " " Then
            ' split the text into the two parts (before and after the space)
            Dim sTextBeforeSpace As String, sTextAfterSpace As String
            sTextBeforeSpace = Left$(sText, 5)
            sTextAfterSpace = Right$(sText, 4)
            ' update the other TextBoxes based on the text in the first part (before the space)
            Select Case sTextBeforeSpace
                Case "P1000": UpdateTextBoxesWithCodes sTextAfterSpace, Tb2, Tb3
                Case "P1018": UpdateTextBoxesWithCodes sTextAfterSpace, Tb4, Tb5
                ' ... add other Case statements as required, adjusting the 'P' code and the names of the TextBoxes
            End Select
        End If
    End If
End Sub


Private Sub UpdateTextBoxesWithCodes(sTextAfterSpace As String, tbLeft As MSForms.TextBox, tbRight As MSForms.TextBox)
    ' if the left TextBox (eg Tb2) is empty then put the text into it, otherwise
    'into the right TextBox (eg Tb3)
    If Len(tbLeft.Text) = 0 Then
        tbLeft.Text = sTextAfterSpace
    Else
        tbRight.Text = sTextAfterSpace
    End If
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.