如果用户取消或不input任何东西到input框如何退出function

在要求用户将文本input到InputBox后,我有一个代码将文本插入到新插入的行中。 我的问题是,如果用户select取消InputBox,代码将仍然运行,它会插入一个新的行,并写入F列F列。如果没有input,我按下OK,那么它将退出该function正确。 但是,如何在用户按下取消时退出该function呢?

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 

问题在于,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。

Application.InputBox()返回False取消,而InputBox()返回"" 。 请参阅联机帮助。

在立即窗口中试试这个:

 ? (InputBox("Click cancel") = "") ? (Application.InputBox("Click cancel") = False) 

两个返回True取消。