2015-08-21 94 views
0

我寫一個程序選擇案例的InputBox不起作用

Sub message() 

    Dim answer As Variant 
    answer = InputBox("Write something") 
    Range("A1").Select 
    ActiveCell.value = answer 
    MsgBox "You wrote: " & answer 

End Sub 

但是當用戶點擊「取消」,它實際上並沒有取消,而是清除單元格A1。

我想是這樣的:

Sub message() 

    Dim answer As Variant 
    answer = Select Case InputBox("Write something") 
    Case vbOK 
     Range("A1").Select 
     ActiveCell.value = answer 
     MsgBox "You wrote: " & answer 

End Sub 

,但沒有奏效。

+1

InputBox如果能夠在執行時按下Cancel來奇蹟般地停止執行其餘代碼,如果按下取消,['vbNullString'返回](http://stackoverflow.com/a/20909528/11683)。 – GSerg

+0

[取消功能的VBA密碼輸入]的可能重複(http://stackoverflow.com/questions/20909417/vba-password-input-with-cancel-function) – GSerg

回答

1

下面是解決方案。

Sub message() 

    Dim answer As Variant 
    answer = InputBox("Write something") 

    If StrPtr(answer) = 0 Then ''if Cancel pressed 
     Exit Sub 
    Else ''if OK pressed 
     Range("A1").Value = answer 
     MsgBox "You wrote: " & answer 
    End If 

End Sub