0

亲爱的,

我想制作一个简单的用户表单来将一些序列号记录到 excel 中,它包含一个 textbox_serialNo.、一个命令按钮“输入”和另一个命令按钮“取消”。

我在那个 serialNo 文本框中做了一个验证控件,所以只能输入数字。但是,当我运行程序并在文本框中输入一些数字时,两个命令按钮(名为 label_enter 的“enter”按钮,名为 label_cancel 的“cancel”按钮)都没有反应(例如,“cancel”按钮没有按时卸载表格),我应该如何更正程序?以下是相关代码,谢谢。

Private Sub TextBox_SerialNo_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
If Not IsNumeric(TextBox_SerialNo.Value) Then
    TextBox_SerialNo.BackColor = rgbYellow
End If
Cancel = True
End Sub

Private Sub TextBox_SerialNo_AfterUpdate()
If TextBox_SerialNo.Value <> "" Then
    TextBox_SerialNo.BackColor = rgbWhite
End If
End Sub

Private sub label_enter_click()
sheet1.Select
Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select
ActiveCell.Value = ActiveCell.Offset(-1, 0).Value + 1
ActiveCell.Offset(0, 1) = TextBox_SerialNo.Value
 TextBox_SerialNo.Value = ""
 End Sub

Private Sub Label_Cancel_Click()
Unload Me
End Sub
4

1 回答 1

0

很抱歉发布作为答案,没有足够的代表。

Cancel=True应该在 if 语句中吗?无论条目是否为数字,您都将其锁定。

编辑:实际上在进一步测试后仍然无法正常工作。但是,更改事件效果更好,您可以获得任何非数字的即时反馈。

更新后的代码如下所示,控件名称不同。我习惯于使用 .Text,与 .Value 相同。此外,由于我不确定您将如何处理空字符串,因此假设它也是黄色背景。

一个问题是,您可以在其中允许逗号或句号吗?根据区域设置,小数也将被视为数字。

Private Sub cmdCancel_Click()

    Unload Me

End Sub

Private Sub cmdEnter_Click()
    
    If TextBox1.BackColor = rgbYellow Then Exit Sub
    test4.Range("A1").Value = TextBox1.Text

End Sub

Private Sub TextBox1_Change()

    If Not IsNumeric(TextBox1.Text) Or TextBox1.Text = "" Then
        TextBox1.BackColor = rgbYellow
    Else
        If TextBox1.Text <> "" Then
            TextBox1.BackColor = rgbWhite
        End If
    End If
    
End Sub

编辑 2:我使用这段代码只检查数字(假设数字 Ascii 代码是标准的)。也许它可以提供帮助。

Public Function isnumber(ByVal strValue As Variant) As Boolean

    On Error Resume Next
    
    Dim i As Long
    
    isnumber = True
    If Not strValue = "" Then
        For i = 1 To Len(CStr(strValue))
            If Asc(Mid(strValue, i, 1)) > 57 Or Asc(Mid(strValue, i, 1)) < 48 Then
                isnumber = False
                Exit For
            End If
        Next i
    Else
        isnumber = False
    End If
    
    On Error GoTo 0
    Err.Clear
    
End Function

编辑 3:我已经修改了 TextBox1_Change 事件代码,因此所有无效字符都被立即删除。但是,在这种状态下,如果您复制粘贴带有不允许的字符的序列号,它将剥离它们,只留下数字。不确定是否可以接受。

Private Sub TextBox1_Change()

    If Not isnumber(TextBox1.Text) Or TextBox1.Text = "" Then
        TextBox1.BackColor = rgbYellow
            
        Dim i As Long
        Dim strValue As String
        
        strValue = ""
        
        If Not TextBox1.Text = "" Then
            For i = 1 To Len(CStr(TextBox1.Text))
                If Not (Asc(Mid(TextBox1.Text, i, 1)) > 57 Or Asc(Mid(TextBox1.Text, i, 1)) < 48) Then
                    strValue = strValue & Mid(TextBox1.Text, i, 1)
                End If
            Next i
        End If
        
        TextBox1.Text = strValue
        
    Else
        If TextBox1.Text <> "" Then
            TextBox1.BackColor = rgbWhite
        End If
    End If
    
End Sub
于 2021-08-08T22:50:38.237 回答