我有兩個較早的答案困難。
我同意驗證是必不可少的;如果用戶對提示認真考慮不周,用戶可能會輸入「2011-4」。檢查其格式是「Q#####」絕對是朝着正確方向邁出的一步。然而:
我會指出,這種檢查水平是不夠的。例如,「Q5 1234」會匹配這種格式。 「Q5 1234」會建議用戶試圖破壞系統,但「Q4 2101」是一個很容易犯的錯誤。
Like操作符是Excel 2003的唯一選擇,但對於更高版本,我建議考慮使用正則表達式。我一直在用VB 2010試驗它們。我不否認它們是一種理解的鬥爭,但它們爲你做了很多。或許重型汽車目前在他的盤子上有足夠的知識,但我仍然會建議查看一些關於其使用的問題。
正如前面的答案中所用,InputBox沒有達到重型槍械的目標。如果我輸入「Q4 2101」而不是「Q4 2011」,並且宏被增強以檢查不可能的日期,我不知道我的簡單錯誤,除非錯誤消息包含我輸入的值。此外,我無法將「Q4 2101」編輯爲我打算輸入的值。 InputBox的語法是vReply = InputBox(提示,標題,默認,...)。所以,如果我要推薦使用該運營商一樣的,我建議:
Sub updatesheet()
Dim vReply As String
Dim Prompt As String
Dim Title As String
Dim UpdateQuarter As Integer
Dim UpdateYear As Integer
' I have found users respond better to something like "Qn ccyy"
Prompt = "Enter period (format: Qn ccyy) to update, or hit enter to escape"
' I find a title that gives context can be helpful.
Title = "Update sheet"
vReply = InputBox(Prompt, Title)
Do While True
' I have had too many users add a space at the end of beginning of a string
' or an extra space in the middle not to fix these errors for them.
' Particularly as spotting extra spaces can be very difficult.
vReply = UCase(Trim(VReply))
vReply = Replace(vReply, " ", " ") ' Does not cater for three spaces
If Len(vReply) = 0 Then Exit Sub
If vReply Like "Q# ####" Then
' I assume your macro will need these value so get them now
' so you can check them.
UpdateQuarter = Mid(vReply, 2, 1)
UpdateYear = Mid(vReply, 4)
' The check here is still not as full as I would include in a macro
' released for general use. I assume "Q4-2011" is not valid because
' the quarter is not finished yet. Is "Q3-2011" available yet? I
' would use today's date to calculate the latest possible quarter.
' I know "You cannot make software foolproof because fools are so
' ingenious" but I have learnt the hard way that you must try.
If UpdateQuarter >= 1 And UpdateQuarter <= 4 And _
UpdateYear >= 2009 And UpdateYear <= 2012 Then
Exit Do
Else
' Use MsgBox to output error message or include it in Prompt
End If
Else
' Use MsgBox to output error message or include it in Prompt
End If
vReply = InputBox(Prompt, Title, vReply)
Loop
End Sub
最後,我很少使用的InputBox因爲形式,一旦掌握,是很容易創建和提供更多的控制權。
謝謝,作品很好^^ – heavyarms 2011-12-16 10:56:22
有沒有簡單的一行我可以添加incse用戶輸入q小寫? – heavyarms 2011-12-16 11:06:17
我已經更新了代碼,以便msgbox將接受「2010年第二季度」或「2010年第二季度」,但會在「2010年第二季度」中輸入這兩種情況的結果 – brettdj 2011-12-16 11:31:12