excel - 如果用户表单文本框值为空或可以在范围列表中找到字符串,如何退出子
问题描述
尽管使用了我在网上找到的许多建议和变体,但我一直在努力解决这个问题。如果用户忘记输入值或者可以在字符串范围内找到该值,我想退出子程序,这与用户表单有关。
这是我为该IF
子句尝试的许多变体中的最新变体:
Private Sub cmd_nProj_Click()
Dim wb As Workbook
Dim ws As Worksheet, ws_h As Worksheet
Dim i_rc As Long
Dim r_home As Range, r_ProdName As Range
Set wb = Application.ThisWorkbook
Set ws_h = wb.Sheets("Control")
i_rc = ws_h.Cells(Rows.Count, 1).End(xlUp).Row
Set r_home = ws_h.Range("A" & i_rc + 1)
Set r_ProdName = ws_h.Range("N2:N30")
If Me.tb_NewProjName = "" Or r_ProdName.Find(What:=Me.tb_NewProjName.Value, LookIn:=xlValues) Is Nothing Then
MsgBox ("Either you have left the projection name blank or the projection name is already being used, please try again!")
Exit Sub
End If
end sub
其他变体我会得到一个带有块变量未设置错误的对象,并且在此迭代中,if 子句无法正常工作,即使文本框值出现在该范围内,也会跳过 if 子句。
提前致谢!
解决方案
即使文本框值出现在该范围内,也会跳过 if 子句。
这是因为当您在范围内找不到值时,您正在退出子程序。我添加了一个Not
来解决这个问题。
Private Sub cmd_nProj_Click()
Dim wb As Workbook
Dim ws As Worksheet, ws_h As Worksheet
Dim i_rc As Long
Dim r_home As Range, r_ProdName As Range
Set wb = Application.ThisWorkbook
Set ws_h = wb.Sheets("Control")
i_rc = ws_h.Cells(Rows.Count, 1).End(xlUp).Row
Set r_home = ws_h.Range("A" & i_rc + 1)
Set r_ProdName = ws_h.Range("N2:N30")
If Me.tb_NewProjName = "" Or Not (r_ProdName.Find(What:=Me.tb_NewProjName.Value, LookIn:=xlValues) Is Nothing) Then
MsgBox ("Either you have left the projection name blank or the projection name is already being used, please try again!")
Exit Sub
End If
End Sub
推荐阅读
- javascript - React.js 路由到“/”会导致 [不能在没有“新”的情况下调用]
- ios - Alamofire 不会自动设置“If-None-Match”标头
- arrays - 如何优化这段代码,让整个过程加速?
- python - 在 Python(tkinter)中从类的外部更改类的私有属性(标签)
- c++ - 我应该如何在 io_service 中解决这个问题?
- android - Jetpack Compose 减少 TextField 的高度
- javascript - 如何在 nodejs 中导入 puppeteer npm
- go - 优雅地停止收听频道的更好方法
- python - 使用 xarray/other 库在 netcdf 文件中组合时间维度
- reactjs - 避免在多个 setState 上重新渲染