2015-08-21 64 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