根据用户输入将条件字符串输入到单元格中

时间:2011-12-16 12:37:27

标签: excel excel-vba vba

这是在前一个问题here之后发生的,其中我询问了如何开发一个input box,要求用户以特定格式输入数据(例如:2010年第4季度)

我现在需要取用户输入的前2个字符(始终为Q1,Q2,Q3或Q4)并根据结果更改另一个单元格中的文本。具体来说,如果用户输入以Q1或Q3开头的字符串,我需要将<insert text1>复制到Sheet3中的单元格中,如果他们输入Q2或Q4,则复制<insert text2>相反的细胞。

我不知道如何只考虑输入的一部分,所以欢迎任何帮助:)

1 个答案:

答案 0 :(得分:3)

您可以尝试使用两个字符串填充名为A1的工作表的Sheet3

[根据msgbox asking for user input in specific format更新了,使用正则表达式进行防弹]

Option Explicit
Sub Rattle_and_hmmmm2()
    Dim strReply As String
    Dim strTitle As String
    Dim objRegex As Object
    Dim objRegMC 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)
    Set objRegMC = .Execute(strReply)
    End With
    Select Case objRegMC(0).submatches(0)
    Case 2, 4
    Sheets("Sheet3").[a1] = "insert text2"
    Case 1, 3
    Sheets("Sheet3").[a1] = "insert text1"
    End Select
    Sheets("Sheet1").[b14].Value = UCase$(strReply)
End Sub