2015-12-03 22 views
0

我有一個代碼插入到新插入的行後,它要求用戶輸入文本到輸入框中的文本。我遇到的問題是,如果用戶在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 

回答

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 

但在這種情況下,你必須定義響應爲Variant。

+0

完美,謝謝! – Chris

0

Application.InputBox()回報上取消False,而InputBox()回報""。請參閱聯機幫助。

試試這個在立即窗口:

? (InputBox("Click cancel") = "") 

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

雙方在取消返回True。

相關問題