msgbox asking for user input in specific format

前端 未结 3 452
我寻月下人不归
我寻月下人不归 2021-01-21 13:16

I\'m trying to write a quick little macro that asks the user for an input, and then copies this to a specific cell (B14 in Sheet1). Here\'s what I\'ve got so far:



        
3条回答
  •  清酒与你
    2021-01-21 13:37

    something like this, you were very close (rather than Inputbox you just needed to use vReply when writing to Sheet1 B14)

    Updated Overhauled to de-hmmm:

    1. Uses Application.InputBox rather than 'InputBox' as this provides the coder with more optionality. But nice to have in this instance rather than critcal
    2. Uses a Regex to ensure that the string is of the form "Q[1-4]" with a year ranging from 2010-2020 (to update to 2011-2013 use "^Q[1-4]\s20[11-13]{2}$". The "q" test is case insensitive
    3. I've added a default entry of "Q1 2011" to the prompt that calcuates using the currentd ate, Int((Month(Now()) - 1) / 3) + 1 & " " & Year(Now()) returns Q4 2011 . You can remove this prompt if desired
    4. A Do loop is used to test invalid strings, if an invalid string is supplied than the strTitle variable of "Please retry"" is used to let the user know that prior attempts were invalid (the msg doesn't show the first time through as the user is yet to make a mistake)
    5. Pressing Cancel triggers a separate exit message to let the user know the code has terminated early

       Option Explicit
      Sub Rattle_and_hmmmm()
      Dim strReply As String
      Dim strTitle As String
      Dim objRegex As Object
      Set objRegex = CreateObject("vbscript.regexp")
      With objRegex
          .ignorecase = True
          .Pattern = "^Q[1-4]\s20[10-20]{2}$"
          Do
              If strReply <> vbNullString Then strTitle = "Please retry"
              strReply = Application.InputBox("Enter period (format: Q4 2010) to update, or hit enter to escape", strTitle, "Q" & Int((Month(Now()) - 1) / 3) + 1 & " " & Year(Now()), , , , , 2)
              If strReply = "False" Then
                  MsgBox "User hit cancel, exiting code", vbCritical
                  Exit Sub
              End If
          Loop Until .test(strReply)
      End With
      Sheets("Sheet1").[b14].Value = UCase$(strReply)
      End Sub
      

提交回复
热议问题