excel - 如果必填字段为空,则禁用命令按钮
解决方案
使用*_Change
每个控件的事件(以及可选的UserForm_Activate
事件)来设置.Enabled
控件按钮的属性。
例如,在具有 1 个 ComboBox ( ComboBox1
)、2 个 TextBox (TextBox1
和TextBox2
) 和 1 个 CommandButton ( CommandButton1
) 的简单用户窗体上,以下代码将确保CommandButton1
禁用它,除非其他 3 个控件中的每个控件中都有数据:
Option Explicit
Private Sub CheckMandatoryFields()
'Is a separate sub to make it easy to edit for all Controls at the same time
If Len(TextBox1.Value) > 0 And Len(TextBox2.Value) > 0 And Len(ComboBox1.Value) > 0 Then
CommandButton1.Enabled = True
Else
CommandButton1.Enabled = False
End If
End Sub
Private Sub CommandButton1_Click()
MsgBox "Button is enabled!"
End Sub
Private Sub ComboBox1_Change()
CheckMandatoryFields
End Sub
Private Sub TextBox1_Change()
CheckMandatoryFields
End Sub
Private Sub TextBox2_Change()
CheckMandatoryFields
End Sub
Private Sub UserForm_Activate()
CheckMandatoryFields
End Sub
如果您的按钮和控件在工作表中,那么您需要更改UserForm_Activate
为Worksheet_Activate
. 如果它们在不同的工作表中,或者一些在工作表中,而另一些在用户窗体中,那么您将需要完全限定您的引用(例如Sheet1.Textbox1.Value
)
如果您在工作表中使用表单控件而不是 ActiveX 控件,则不能使用_Change
事件,并且引用对象的方式不同:
Sheet1.Shapes("TextBox1").TextFrame2.TextRange.Text 'The value of TextBox1
Sheet1.Shapes("ComboBox1").ControlFormat.Value 'Which Number item in ComboBox1 is selected
Sheet1.Shapes("ComboBox1").ControlFormat.List(n) 'The value of the nth item in ComboBox1
表单控件按钮没有Enabled
属性 - 但是,如果你有一个“什么都不做”宏,你可以像这样躲避它:
Sub DoNothing()
'As it says
End Sub
Sub MakeASound()
Beep
End Sub
Sub ToggleButton()
If Sheet1.Shapes("Button 1").OnAction = "Sheet1!DoNothing" Then 'Disable Button 1
Sheet1.Shapes("Button 1").OLEFormat.Object.Font.ColorIndex = 16 'Font colour = Grey
Sheet1.Shapes("Button 1").OnAction = "Sheet1!DoNothing"
Else 'Enable Button 1
Sheet1.Shapes("Button 1").OLEFormat.Object.Font.ColorIndex = 1 'Font colour = Black
Sheet1.Shapes("Button 1").OnAction = "Sheet1!MakeASound"
End If
End Sub
推荐阅读
- selenium - 在 selenium 中调用网站时,该页面未登录到我的谷歌帐户
- python - 在 M1 Mac 上的 Python 中使用 OPENCV 导入错误
- spring - 如何从 MockServer 取消绑定 RestTemplate?
- webpack - 在我的 webpack (nuxt) 项目中导入其他模块使用的模块
- python - Scipy最小化与变量总和的约束?
- python - 使用 pip 安装 pyinstaller 的问题
- maven - 需要在里面执行一些参数
- react-router - history.push 替换最后一条路径
- javascript - 在 chrome devtools 中使用 javascript 获取截断工具提示的完整文本
- google-sheets - Gspread 将 Google Sheet 读取为数据框