亲爱的们:
我想做一个简单的用户表单来记录一些序列号到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发布于 2021-08-08 22:50:38
很抱歉作为一个答案张贴,没有足够的代表。
Cancel=True不应该在if语句中吗?无论条目是否为数字,您都会将其锁定。
编辑:实际上在进一步的测试中仍然不能正常工作。但是,change事件的效果更好,您可以获得任何非数字的即时反馈。
更新的代码看起来像这样,控件名称不同。和.Value一样,我习惯于使用.Text。此外,由于我不确定您将如何处理空字符串,因此假设它也是黄色背景。
一个需要关注的问题是,您是否可以在其中使用逗号或句号?根据区域设置的不同,小数也会被视为数字。
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 Subhttps://stackoverflow.com/questions/68690049
复制相似问题