用户表单验证

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

我正在尝试创建一个包含 7 个文本框的用户表单,其中文本框的每个答案将被放置到另一张“Bulk Loader”工作表的不同列中。我需要在现有代码中添加一个代码,其中如果文本框 1 到文本框 5 之间的文本框之一未填写,答案将不会提交到表 2。这是我现有的代码。

Private Sub CommandButton1_Click()

Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Bulk Loader")
Dim n As Long

n = sh.Range("A" & Application.Rows.Count).End(xlUp).Row

sh.Range("A" & n + 1).Value = TextBox1.Value
sh.Range("B" & n + 1).Value = TextBox2.Value
sh.Range("C" & n + 1).Value = TextBox3.Value
sh.Range("D" & n + 1).Value = TextBox4.Value
sh.Range("E" & n + 1).Value = TextBox5.Value
sh.Range("F" & n + 1).Value = TextBox6.Value
sh.Range("G" & n + 1).Value = TextBox7.Value

 If TextBox1.Value <> "" And TextBox2.Value <> "" And TextBox3.Value <> "" And TextBox4.Value <> "" And TextBox5.Value <> "" And TextBox6.Value <> "" And TextBox7.Value <> "" Then
    
    MsgBox "IPO Details Added", vbOKOnly + vbInformation, "ERROR"
    
    Unload Me
    
    Exit Sub
    
    End If
    
    If TextBox1.Value = "" Then
        MsgBox "User ID can't be filled blank", vbOKOnly + vbCritical, "ERROR"
        
    End If
    
    If TextBox2.Value = "" Then
        MsgBox "Please enter Launch Date", vbOKOnly + vbCritical, "ERROR"
        
    End If
    
    If TextBox3.Value = "" Then
        MsgBox "Please input Date", vbOKOnly + vbCritical, "ERROR"
        
    End If
    
    If TextBox4.Value = "" Then
        MsgBox "Please input Price", vbOKOnly + vbCritical, "ERROR"
        
    End If
    
    If TextBox5.Value = "" Then
        MsgBox "Please enter Launch Price ", vbOKOnly + vbCritical, "ERROR"
        
    End If
       
    Exit Sub
    
    If response = "vbOKOnly" Then DATA_ENTRY.Show
    
    Exit Sub
    
End Sub
excel vba
1个回答
0
投票

如果您告诉用户缺少的所有内容,而不是一一告诉他们,这对用户来说会更好。

例如:

Private Sub CommandButton1_Click()
    Dim sh As Worksheet, msg As String
    
    'check for any empty required fields
    If Len(TextBox1.Value) = 0 Then msg = msg & vbLf & " - User ID"
    If Len(TextBox2.Value) = 0 Then msg = msg & vbLf & " - Launch Date"
    If Len(TextBox3.Value) = 0 Then msg = msg & vbLf & " - Date"
    If Len(TextBox4.Value) = 0 Then msg = msg & vbLf & " - Price"
    If Len(TextBox5.Value) = 0 Then msg = msg & vbLf & " - Launch Price"
    
    If Len(msg) > 0 Then 'anything missing?
        MsgBox "The following fields are required:" & msg, _
                vbOKOnly + vbCritical, "Missing Information"
    Else
        'OK to write to sheet
        Set sh = ThisWorkbook.Sheets("Bulk Loader")
        With sh.Cells(Rows.Count, "A").End(xlUp).Offset(1)
            .Resize(1, 7).Value = Array(TextBox1.Value, TextBox2.Value, _
                                  TextBox3.Value, TextBox4.Value, TextBox5.Value, _
                                  TextBox6.Value, TextBox7.Value)
        
        End With
    End If
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.