【问题标题】:MsgBox if value in userform does not equal to ranges on sheet如果用户窗体中的值不等于工作表上的范围,则 MsgBox
【发布时间】:2018-08-08 16:27:01
【问题描述】:

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

【问题讨论】:

  • 你必须在IF/OR的每个部分添加比较&lt;&gt; Me.textbox..
  • 这就是答案。请不要在 cmets 中写答案。这会误导像我这样寻找未解决问题的人。另外,我会在每个单独的比较中添加括号,以使其更具可读性。
  • @ComradeMicha - 这确实是答案 - 意味着更有用的提示,因为一个完整的答案(即将发布)将解决代码的其他问题,包括变量声明(只有 raw5 是 @987654324 @,其他都是Variant
  • 对不起,小错误我没有添加到我的代码中,但我编辑了原始帖子以添加比较代码(2 次比较只是为了检查代码),它仍然没有执行。跨度>
  • 你也想要And而不是Or

标签: excel vba


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-17
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    相关资源
    最近更新 更多