2014-07-17 127 views
0

好日子Excel宏用戶輸入,循環回用戶重新輸入,如果不正確

我試圖把用戶輸入和更新範圍的基礎上,一個表,但被陷在詢問IM用戶在與任何預定義條目不匹配的情況下「重新輸入」他的輸入。

下面

是我的代碼

Sub testing_input_in_formula() 

Dim wbk1 As Workbook 
Dim strName As String 

test1 = "C:\Users\hayekn\Desktop\book1.xlsx" 

Set wbk1 = Workbooks.Open(test1) 

With wbk1.Sheets("Sheet1") 

On Error Resume Next 

    Application.DisplayAlerts = True 

    strName = InputBox(Prompt:="Enter the week you would like to update", _ 
    Title:="Week Selection.", Default:="Week 1") 

    If strName = "Your Name here" Or _ 
    strName = vbNullString Then 

Exit Sub 

    Else 

    Select Case strName 

    Case "Week 1" 
    .Range("A10") = "Week 1" 

    Case "Week 2" 
    .Range("B10") = "Week 2" 

    Case Else 
    MsgBox "Incorrect Entry." 
    'I want it here to loop back to the "Select Case strName", 
    'where user is prompted to re-enter the text 

    End Select 

    End If 

End With 

End Sub 

回答

2

你可以使用一些線標籤和Goto線之間跳轉如下:

Sub testing_input_in_formula() 

Dim wbk1 As Workbook 
Dim strName As String 
Dim test1 As String 

test1 = "C:\Users\hayekn\Desktop\book1.xlsx" 
Set wbk1 = Workbooks.Open(test1) 
'On Error Resume Next <- Why do you need this? 
Application.DisplayAlerts = True 

Re-Enter: 

strName = InputBox(Prompt:="Enter the week you would like to update", _ 
Title:="Week Selection.", Default:="Week 1") 

If strName = "Your Name here" Or strName = vbNullString Then 
    Goto The_End 
Else 
    With wbk1.Sheets("Sheet1") 
     Select Case strName 
      Case "Week 1" 
       .Range("A10") = "Week 1" 
      Case "Week 2" 
       .Range("B10") = "Week 2" 
      Case Else 
       MsgBox "Incorrect Entry." 
       ' if you want the user to re enter the text you should loop to the InputBox 
       Goto Re-Enter 
     End Select 
    End With 
End If 

The_End: 
Set wbk1 = Nothing 

End Sub 

請注意,我重新安排了一些代碼,添加TEST1變量,將工作表設置爲Nothing。這些都是你將來需要的良好習慣:) 請看看here瞭解「無所事事」的含義

+0

真棒!像一個魅力工作:)並感謝您的改善。我是初學者,不知道如何使用最佳實踐。再次感謝 !! – Nadz

+0

不用擔心,社區在這裏幫助:) – Noldor130884

相關問題