首页 > 解决方案 > 如果用户窗体中的值不等于工作表上的范围,则 MsgBox

问题描述

如果我的用户表单中输入的值与我的 Excel 工作表上的 5 个单元格值中的任何一个都不匹配,我正在尝试显示一个消息框。到目前为止,我已经为单个单元格值工作,但是当我为其他值添加“或”时它不起作用。

Private Sub cmdEnterData_Click()

Dim raw1 As Range, raw2 As Range, raw3 As Range, raw4 As Range, raw5 As Range

Set raw1 = Range("A1")
Set raw2 = Range("A2")
Set raw3 = Range("A3")
Set raw4 = Range("A4")
Set raw5 = Range("A5")

' this one works for referencing a single cell value

If Trim(raw1.Value) <> Me.textbox_RawItem.Value Then
MsgBox "This item does not match the item list"
 With Me.textbox_RawItem
  .SetFocus
  .SelStart = 0
  .SelLength = Len(.Text)
 End With
 Exit Sub
End If

' this one does NOT work 

If Trim(raw1.Value) <> Me.textbox_RawItem.Vaule Or Trim(raw2.Value)<> 
Me.textbox_RawItem.Value Then
MsgBox "This item does not match the item list"
 With Me.textbox_RawItem
  .SetFocus
  .SelStart = 0
  .SelLength = Len(.Text)
 End With
 Exit Sub
End If

标签: excelvba

解决方案


BigBen 使用“And”而不是“Or”是正确的。代码是这样工作的:

Private Sub cmdEnterData_Click()

Dim raw1 As Range, raw2 As Range, raw3 As Range, raw4 As Range, raw5 As Range

Set raw1 = Range("A1")
Set raw2 = Range("A2")
Set raw3 = Range("A3")
Set raw4 = Range("A4")
Set raw5 = Range("A5")


If Trim(raw1.Value) <> Me.textbox_RawItem.Value And Trim(raw2.Value) <> 
Me.textbox_RawItem.Value And Trim(raw3.Value) <> Me.textbox_RawItem.Value And 
Trim(raw4.Value) <> Me.textbox_RawItem.Value And Trim(raw5.Value) <> 
Me.textbox_RawItem.Value Then
MsgBox "This item does not match the item list"
 With Me.textbox_RawItem
  .SetFocus
  .SelStart = 0
  .SelLength = Len(.Text)
 End With
Exit Sub
End If

推荐阅读