Excel输入框以最大数量打印多少份副本

时间:2016-11-16 15:31:11

标签: excel vba excel-vba

我需要一个输入框来询问要打印的副本数量,允许输入最大数量。

我有以下代码,但有效但如果我输入的数字超过“1”则触发了 If NumberOfCopies >= "11" Then如果我点击取消按钮,它也会触发同样的事情

'ASKS HOW MANY COPIES TO PRINT
PRINTS:
Dim NumberOfCopies As String
NumberOfCopies = Application.InputBox("How many copies do you want to print? Must enter 0-10", Type:=2)

If NumberOfCopies >= "11" Then
MsgBox "Max to print is 10 copies"
GoTo PRINTS
End If

If NumberOfCopies = "0" Or NumberOfCopies = "" Then
'do not print
Else
ActiveSheet.PrintOut Copies:=NumberOfCopies
End If

3 个答案:

答案 0 :(得分:2)

将数字放在引号中会将它们转换为字符串。由于您希望用户输入数字,因此您应进行以下更改:

    Dim NumberOfCopies As Int
NumberOfCopies = Application.InputBox("How many copies do you want to print Must enter 0-10", Type:=1)

If NumberofCopies >= 11 Then
...

If NumberOfCopies = 0 or NumberOfCopies = "" Then
...

答案 1 :(得分:2)

还需要测试用户点击取消...这在我点击取消或输入0,1或11时适用于我

Prints:
Dim NumberOfCopies As String
NumberOfCopies = Application.InputBox("How many copies do you want to print? Must enter 0-10", Type:=2)

If NumberOfCopies = "False" Or NumberOfCopies = "0" Then
  'If user hits Cancel, NumberofCopies will be "False"
Else
  If NumberOfCopies >= "11" Then
    MsgBox "Max to print is 10 copies"
    GoTo Prints
  Else
    ActiveSheet.PrintOut Copies:=NumberOfCopies
  End If
End If

答案 2 :(得分:1)

Type:=2实际上是Text类型。您正在使用数字,因此您应将其设置为Type:=1。这样,如果用户输入的不是数字,它将自动弹出一个消息“数字无效”(不需要编写脚本)。

您还应该尽可能避免使用位置标签。您的代码可以使用Do...While循环轻松编写脚本。

正如已经指出的那样,在处理数字时,不要将它们用双引号括起来,否则VBA会将它们视为String(这不是你想要的)。

@Rdster为用户点击“取消”按钮带来了一个很好的观点。当发生这种情况时,变量的值将为“False”(字符串),因此您应该查找它。

说完所有这些,我相信你的代码会更好地运作:

'ASKS HOW MANY COPIES TO PRINT
Dim NumberOfCopies As String
Do
    NumberOfCopies = Application.InputBox("How many copies do you want to print? Must enter 0-10", Type:=1)
    If NumberOfCopies = "False" Then Exit Sub   ' If user clicks on Cancel button
    If NumberOfCopies > 10 Then
        MsgBox "Max to print is 10 copies"
    End If
Loop While NumberOfCopies > 10    'although producing the same result, it is cleaner to compare with 10, than to >=11

'Avoid leaving blank conditions. Work with what you have.
'Everything that doesn't match your conditions will be skipped anyways.
If NumberOfCopies > 0 And NumberOfCopies < 10 Then
    ActiveSheet.PrintOut copies:=NumberOfCopies
End If