MsgBox,如果用户窗体中的值不等于图纸上的范围

时间:2018-08-08 16:27:02

标签: excel-vba

如果用户表单中输入的值与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

1 个答案:

答案 0 :(得分:0)

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