Excel VBA:检查以确保所有控件不是空的

在我的程序中,我在userfrom中有一段代码,它查看自己的控件并循环查看它们是否全部为空。 这是为了将所有非空控件的值用作搜​​索参数。 他们是三个列表框和三个combobox。 如果它find一个不为空的控件,它会将该函数设置为false并退出。 这是因为我的searchfind了一个可以使用的标准。 我有这样的设置:

Function IsAllEmpty() As Boolean 'presumes true until we find evidence of a control being not empty IsAllEmpty = True 'function elsewhere that sets my control background to normal ClearControlFormatting Dim ctrl As Control 'checks every control in the form For Each ctrl In Me.Controls 'that is tagged with "searchme" (there are 6, three listbox, three combobox) If ctrl.Tag = "SEARCHME" Then 'if the value of the control isn't null or len = 0 If Not IsNull(ctrl) Or Len(ctrl) <> 0 Then ctrl.BackColor = vbGreen IsAllEmpty = False 'in my other code, I can continue the search if this is triggered MsgBox "Everything is good (no sarcasm) on this control!" Exit Function Else: MsgBox "EVERYTHING IS EMPTY, CARL. THAT KILLS PEOPLE." End If End If Next 'If something is empty, tell the user to correct it If IsAllEmpty = True Then MsgBox "YOU NEED TO FILL OUT YOUR SEARCH, PAUL." End If End Function 

我已经尝试了各种各样的事情来得到这个工作:

  • 在If,If Len(ctrl)<> 0部分(IDK WHY)中嵌套非IsNull(ctrl)
  • 删除Len(ctrl)<> 0部分
  • 编辑Or语句的两个部分来评估ctrl.Value =“”
  • 从combobox中移除“SEARCHME”标签,以防dynamic值干扰。

不过,每次我都看过这个function,把我所有的控件都突出显示为绿色,然后继续尝试search。 (在search中调用的函数表示如果所有的单元格都返回null,则退出该子单元)。

我很茫然,非常感谢帮助! 谢谢!

PS:如果有帮助,上面的代码是以下的修改版本,意在检查是否存在任何空的控件。 当我用这个控件的时候,发现它们都是空的,像devise一样工作。

 Function CheckForEmpty() As Boolean CheckForEmpty = True ClearControlFormatting Dim ctrl As Control 'Checks each control that needs to be filled for null or 0 length value 'For every one it finds, it marks red CheckForEmpty = True For Each ctrl In Me.Controls If ctrl.Tag = "FILL" Then If IsNull(ctrl) Or Len(ctrl) = 0 Then ctrl.BackColor = vbRed CheckForEmpty = False End If End If Next 'If something is empty, tell the user to correct it If CheckForEmpty = False Then MsgBox "Please fill out red boxes!" End If End Function 

在这一行中,更改为明确表示您正在查找该值:

If Not IsNull(ctrl) Or Len(ctrl) <> 0 Then

改成:

If (Not IsNull(ctrl.Value)) OR (Len(ctl.Value & "") <> 0) Then

首先,我将.Value限定符添加到控件。 这是默认属性,但有时(例如分配给一个变体或者检查null时),它可能会检查控制本身是否为空,因为VBA并不总是足够聪明来阅读你的想法,而你在技术上告诉它检查控制,而不是它的价值:是明确的。

其次,我明确地将两个支票用括号分成两个单独的支票。 不确定它是严格要求的,但是最好是清晰易读,现在我们不必担心它可能错误地读取了布尔逻辑。

第三,我添加了一个ZLS连接到.Value,如果在检查长度之前,强制它为ZLS(如果试图检查一个空值的Len(),你会得到'无效使用NULL'错误)。

正如Tom提到的,在这种情况下,ctrl永远不会是null(因为它是表单集合的一部分,它不会有null引用),所以整个事情可以简化为:

If Len(ctrl.Value & "") <> 0 Then 'ctrl has no value entered

最后,将它封装在一个Trim()函数中,以防在那里有一个(或两个或更多)空间,并且你有:

If Len(Trim(ctrl.Value & "")) <> 0 Then 'ctrl has no meaningful value entered