如果在执行以下 VBA 代码后,一些 Double 数值型文本框和其他文本型文本框没有清空,可能是因为这些文本框的数据类型不兼容或存在其他属性限制。

Private Sub CommandButton3_Click()
    Dim ctl As Control
    
    For Each ctl In Me.Controls
        If TypeOf ctl Is TextBox Then
            ctl.Text = ""
        ElseIf TypeOf ctl Is ComboBox Then
            ctl.Text = ""
        ElseIf TypeOf ctl Is ListBox Then
            ctl.Text = ""
        ElseIf TypeOf ctl Is CheckBox Then
            ctl.Value = False
        ElseIf TypeOf ctl Is OptionButton Then
            ctl.Value = False
        End If
    Next ctl
End Sub

在这种情况下,你可以尝试使用 ctl.Object.Text 属性来清空文本型的控件,并使用 ctl.Object.Value = Empty 来清空 Double 数值型的控件。这样可以确保无论是文本型还是数值型文本框都能成功清空。

以下是修改后的代码示例:

Private Sub CommandButton3_Click()
    Dim ctl As Control
    
    For Each ctl In Me.Controls
        If TypeOf ctl Is TextBox Then
            If TypeName(ctl.Object) = "TextBox" Then
                ctl.Object.Text = ""
            ElseIf TypeName(ctl.Object) = "DoubleTextBox" Then
                ctl.Object.Value = Empty
            End If
        ElseIf TypeOf ctl Is ComboBox Then
            ctl.Text = ""
        ElseIf TypeOf ctl Is ListBox Then
            ctl.Text = ""
        ElseIf TypeOf ctl Is CheckBox Then
            ctl.Value = False
        ElseIf TypeOf ctl Is OptionButton Then
            ctl.Value = False
        End If
    Next ctl
End Sub

在上面的代码中,我们使用 TypeName(ctl.Object) 来获取控件的类型名称,并针对不同类型的文本框执行不同的清空操作。

注意,你可能需要根据你的实际文本框类型进行适当的修改。此外,确保你的文本框对象具有 Object 属性,以便访问其相应的方法和属性。

此代码应写入窗体的代码模块中,而不是常规模块中。

VBA 清空文本框:解决 Double 数值型文本框无法清空问题

原文地址: https://www.cveoy.top/t/topic/10i 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录