vba MsgBox vbOKCancel 在单元格中留下 1 或 2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18220971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 22:44:43  来源:igfitidea点击:

MsgBox vbOKCancel leaves 1 or 2 in cell

excel-vbavbaexcel

提问by Kojo Jojo

I am using an inputbox with type 8 (cell reference / range). Part of the validation of the selected range is with the MsgBox below.

我正在使用类型为 8(单元格引用/范围)的输入框。所选范围的部分验证是使用下面的 MsgBox 进行的。

The problem is that when you select a wrong range and the MsgBox prompts you, if you click Okit leaves the number 2 in the cell, and if you click Cancelit leaves the number 1 in the cell.

问题是,当您选择错误的范围并且 MsgBox 提示您时,如果单击Ok它会在单元格中留下数字 2,如果单击Cancel它会在单元格中留下数字 1。

ElseIf myRange.Value = "" Or myRange.Value = 0 Then   

  '... 

   myRange = MsgBox("Please Select a Valid Code. Try again?", vbOKCancel + vbQuestion)
   If myRange = vbCancel Then 'No retry
       Exit Sub
   Else 'retry
       Run "MyCellToCorrect"
   End If

Else

采纳答案by Ken White

You're assigning the return value of MsgBox, which will be either vbOK(1) or vbCancel(2), to the range. You should be assigning it to a numeric variable instead, and then testing that variable:

您正在将 的返回值(MsgBoxvbOK(1) 或vbCancel(2))分配给范围。您应该将其分配给数字变量,然后测试该变量:

Dim Res As Integer
....

Res = MsgBox("Please Select a Valid Code. Try again?", vbOKCancel + vbQuestion)
If Res = vbCancel Then 'No retry
    Exit Sub
Else 'retry
    Run "MyCellToCorrect"
End If