我有一个代码,在要求用户将文本输入到InputBox之后,将文本插入到新插入的行中。我遇到的问题是,如果用户在InputBox上选择取消,代码仍然会运行并且它将插入一个新行并将FALSE写入E列。如果没有输入任何内容我按OK,那么它将正确退出函数。但是,如何在用户按下取消时退出该功能?
Public Function ContactAdd() As Long
Dim cF As Range
Dim Response As String
With Worksheets("Database").Range("B:B")
'Find the cell in column B containing value in combobox
Set cF = .Find(What:=Worksheets("Database").ComboBox1, After:=.Cells(1, 1), LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
'If cell in column B is found
If Not cF Is Nothing Then
'Open inputbox
Response = Application.InputBox("Enter contact name")
'If inputbox is cancelled, exit function
If Response = "" Then
MsgBox "Invalid - Exiting"
Exit Function
Else
'If entry to inputbox is made, insert row below the combobox value that was found and paste response into column E of the row that was inserted
cF.Offset(1, 0).EntireRow.Insert
ContactAdd = cF.Offset(1, 0).Row
Worksheets("Database").Cells(ContactAdd, 5).Value = Response
End If
Exit Function
End If
End With
ContactAdd = 0
End Function
Private Sub InsertContact1_Click()
'Execute ContactAdd function when button is clicked
ContactAdd
End Sub
我的代码的这部分因此是不正确的,我不知道为什么......我尝试过使用vbNullString代替""并没有帮助。
If Response = "" Then
MsgBox "Invalid - Exiting"
Exit Function
答案 0 :(得分:2)
问题是,Application.InputBox与“普通”InputBox不同。所以如果你使用:
Response = InputBox("Enter contact name")
'If inputbox is cancelled, exit function
If Response = "" Then
MsgBox "Invalid - Exiting"
Exit Function
End If
它会起作用。如果要使用Application.InputBox,则必须将IF语句更改为:
If Response = False Then
但在这种情况下,您必须将Response定义为Variant。
答案 1 :(得分:0)
Application.InputBox()
在取消时返回False
,而InputBox()
则返回""
。请参阅在线帮助。
在立即窗口中尝试此操作:
? (InputBox("Click cancel") = "")
? (Application.InputBox("Click cancel") = False)
两者都在取消时返回True。