2016-11-16 21 views
2

我需要一個輸入框來詢問允許輸入的最大數量的打印份數。Excel輸入框最多可打印多少份副本

我有下面的代碼,但它的工作原理,但如果我輸入大於「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 
+1

CINT(NumberOfCopies)> = 11 –

+0

當我運行它,你有它的方式,它正確評估。在輸入框中輸入1將移動if語句作爲「1」<「11」。 – Rdster

回答

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 
+1

我除去引號上'如果NumberOfCopies> = 「11」 Then' 碰巧'如果NumberOfCopies = 「假」 或者NumberOfCopies = 「0」 Then' 到'如果NumberOfCopies = 「假」 或者NumberOfCopies =「 0「或者NumberOfCopies =」「Then'因此,如果用戶在輸入框爲空時單擊確定,它將執行與輸入0相同的操作。 – luke

2

把號碼引號將它們變成一個String。既然你想讓用戶輸入一個數字,你應該做如下修改:

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

Type:=2實際上是用於文本類型。您正在使用數字,因此您應將其設置爲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