长时间听众,第一次来电。
我在Excel 2010中遇到VBA问题。我正在尝试比较用户表单上的各个字段以确定它们是否为空。然后我会突出显示红色,并将焦点放在列表中的第一个上。
为此,我为每种类型创建了可以为空/未选中的函数。他们都被宣布为AS BOOLEAN
。我的想法是进行函数调用以突出显示,使用适当的子函数传递函数调用,并使用高亮函数中的结果:
function Blah(DoThis01(Me.Object1), DoThis02(Me.Object2), ...) As Boolean
这让我很高兴;价值总是假的。所以我创建了三个布尔变量来分配这些函数的值,并且它开始通过参考错误给我提供。在声明每个变量而不是全部在一行之后,这解决了byref,但现在我得到了类型不匹配:
Dim foo As Boolean
foo = DoThis01(Me.Object1)
if Blah(foo, bar, ..)
它不喜欢那条中心线;这就是我遇到错误的地方。
下面是我正在使用的代码片段,以及我尝试传递的函数示例。我无法弄清楚为什么我的As布尔函数与As布尔变量不兼容。此外,确定字段是否填充的函数也给我一些问题,而不是注册正确的值。谷歌有很多答案,但迄今为止没有一个对我有用。我很感激您提供的任何见解。
谢谢,
Ĵ
PS我意识到触发消息时某些逻辑可能有点失效。没关系,因为无论如何我都没有得到正确的价值观。如果我可以让其余的工作,我会清理它。
工作代码:
保存按钮:
Dim emptyRow As Long
Dim isDuplicate As Boolean, nameSelect As Boolean, comboSelect As Boolean, listSelect As Boolean
Dim listLength As Integer
Dim blah As Integer
' check for empty on form
nameSelect = IsSelectedName(Me.SignalNameTxtBox)
comboSelect = IsSelectedCombo(Me.ComboBox1)
listSelect = IsSelectedList(Me.ListBox1)
If HighlightEmpty(nameSelect, comboSelect, listSelect) Then
blah = MsgBox("Empty fields required!", vbOKOnly)
Exit Sub
End If
......更多东西
要突出显示空表单对象:
Function HighlightEmpty(nameSelect As Boolean, comboSelect As Boolean, listSelect As Boolean) As Boolean
' Highlight empty fields
If Not nameSelect Then Enter_New_Form.SignalNameTxtBox.BackColor = RGB(255, 0, 0)
If Not comboSelect Then Enter_New_Form.ComboBox1.BackColor = RGB(255, 0, 0)
If Not listSelect Then Enter_New_Form.ListBox1.BackColor = RGB(255, 0, 0)
' Set focus to first empty field on form
If Not nameSelect Then
Enter_New_Form.SignalNameTxtBox.SetFocus
ElseIf Not comboSelect Then
Enter_New_Form.ComboBox1.SetFocus
ElseIf Not listSelect Then
Enter_New_Form.ListBox1.SetFocus
End If
' Return boolean to trigger message
HighlightEmpty = nameSelect Or comboSelect Or Not listSelect
End Function
我确定是否为空的功能:
Function IsSelectedList(lst As ListBox) As Boolean
Dim I As Integer
For I = 0 To lst.ListCount - 1
IsSelectedList = lst.Selected(I)
If IsSelectedList Then Exit Function
Next I
End Function
Function IsSelectedCombo(cbo As ComboBox) As Boolean
If cbo.Value = "" Then IsSelectedCombo = False
End Function
Function IsSelectedName(nme As TextBox) As Boolean
If nme.Value = "" Then IsSelectedName = False
End Function
答案 0 :(得分:1)
除非另有声明为true,否则您的函数将始终返回false。添加如下的else语句:
Function IsSelectedName(nme As TextBox) As Boolean
If nme.Value = "" Then
IsSelectedName = False
Else
IsSelectedName = True
End If
End Function
正如@Timwilliams指出,由于nme.Value = ""
将评估为True
或False
,因此您可以将其减少到一行。但是,您可能会发现,您需要以isBlank()
和isEmpty()
等其他方式测试单元格是否为空。在这种情况下,请使用前面的示例。
Function IsSelectedName(nme As TextBox) As Boolean
IsSelectedName = Len(nme.Value) > 0
End Function
修改强>
要检查值,只需将文本字符串传递给函数而不是文本框对象。试试这个:
Private Sub CommandButton1_Click()
MsgBox (IsSelectedName(Me.SignalNameTxtBox.Text))
End Sub
Function IsSelectedName(nme As String) As Boolean
IsSelectedName = Len(nme) > 0
End Function