Search code examples
vbaexcel-2013

Setting Tag Property of UserForm TextBox


I need some help with setting the Tag Property of a TextBox in a UserForm when the form activates and then checking to make sure that the Text Boxes with that Tag match the conditions when the Save Button is clicked. I believe the issue to be with how I am setting the tag property when the UserForm activates, but I wouldnt be surprised if there is something wrong in the logic of the code when the UserForm Activates. Thank you in advance for your assistance.

Code for when the UserForm Activates:

Private Sub UserForm_Activate()
    Dim i As Long

        For Each ctrl In UWchecklist.Controls
            Select Case TypeName(ctrl)
                Case Is = "ComboBox"
                    If ctrl.Tag = "yesno" Then
                        ctrl.RowSource = "YesNo"
                    End If
                    ctrl.Font.Size = 10
                Case Is = "TextBox"
                    ctrl.Font.Size = 10
                        For i = 1 To 30
                            If ctrl.Name = ("uwtxTB" & i) Then
                                ctrl.Tag = "Check"
                            End If
                        Next i
            End Select
        Next ctrl
End Sub

Code for when the Save Button is Clicked:

Private Sub SandCont_Click()

    For Each ctrl In UWchecklist.Controls
        If TypeName(ctrl) = "TextBox" Then
            If ctrl.Tag = "Check" Then
                If Not ctrl.Value = vbNullString And Not ctrl.Value = "X" Or Not ctrl.Value = "NA" Then
                    ctrl.Value = vbNullString
                    ctrl.BackColor = vbRed
                    MsgBox "Only a value of " & "X " & "or " & "NA " & "is allowed.", 0, "DATA ENTRY ERROR"
                End If
            End If
        End If
    Next ctrl

End Sub

Solution

  • I figured it out; the issue wasn't in the UserForm Activate. It was in the Save and Cont Code. I dont think I was looking at enough of the If conditions, so I set up a Select Case and it works now. It's probably not the most elegant solution.

    For Each ctrl In UWchecklist.Controls
        If ctrl.Tag = "Check" Then
            Select Case ctrl.Value
                Case Is = ""
                    ctrl.BackColor = vbWhite
                Case Is = "X"
                    ctrl.BackColor = vbWhite
                    ctrl.Text = "X"
                Case Is = "NA"
                    ctrl.BackColor = vbWhite
                    ctrl.Text = "NA"
                Case Is <> "X"
                    ctrl.Value = vbNullString
                    ctrl.BackColor = vbRed
                Case Is <> "NA"
                    ctrl.Value = vbNullString
                    ctrl.BackColor = vbRed
            End Select
        End If
    Next ctrl
    
    MsgBox "Only a value of " & "X " & "or " & "NA " & "is allowed.", 0, "DATA ENTRY ERROR"