VBA输入框和目标单元格

时间:2019-03-05 15:38:27

标签: excel vba

我当前有一个工作簿,其中,当作业完成时,用户从G列的下拉框中选择完成,当单元格更改为完成时,将出现一个消息框,提示用户在同一行中输入Y或N我想使用输入框代替Y或N的消息框,但不知道如何将答案输入到M列的正确单元格中。有人能指出我正确的方向吗?以下是我目前拥有的。预先感谢。

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("G:G")) Is Nothing Then
        If Target = "COMPLETE" Then
            MsgBox "If Warranty job  please enter Y in correct cell in column M"
        End If
    End If
End Sub 

2 个答案:

答案 0 :(得分:2)

  

我想使用输入框而不是消息框

友善的忠告:不。然后,您必须控制用户输入,这可以是任何东西。在这个使用InputBox的示例中,我们必须Trim输入,仅采用结果的最左字符,并强制使用一致的大小写,否则我们必须考虑是否“ y” =“ Y” =“ YES” =“ yes” =“ YeS”,等等……并可能处理无效的输入(如果用户输入“ G”或“ 123456789”等,该如何处理),这在实际上不是这样的情况下会增加更多的复杂性需要。

Dim userInput as String
GetUserInput:
userInput = InputBox("Is this a warranty job? Y/N")
userInput = UCase(Left(Trim(userInput),1)
If userInput = "Y" Then

    ' put the value "Y" in column G
ElseIf userInput = "N" Then
    ' do nothing
Else
    ' If user input is not Y or N, send them back to the input box
    GoTo GetUserInput
End If

当然,您可以可以执行此操作,但是对于一个简单的是/否选项,MsgBox实际上是使用标准按钮选项设计的,可以很容易地容纳这一点。 / p>

相反,使用带有选项“是/否”的MsgBox并直接控制对工作表的输入,而不是提示用户手动进行输入。在下面的示例中,我将“ Y”放置在Target单元格的同一行的M列中。根据需要进行修改。

Private Sub Worksheet_Change(ByVal Target As Range)
Dim mbResponse as VbMsgBoxResult

If Not Intersect(Target, Range("G:G")) Is Nothing Then
    If Target = "COMPLETE" Then
        mbResponse = MsgBox("Is this a warranty job?", vbYesNo)
        If mbResponse = vbYes Then
            Target.Offset(0, 6).Value = "Y"

        Else:
            'do nothing

        End If
    End If
End If
End Sub

答案 1 :(得分:2)

如何进行:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("G:G")) Is Nothing Then
        If Target = "COMPLETE" Then
            roww = Target.Row
            Application.EnableEvents = False
                Cells(roww, "M").Value = Application.InputBox(Prompt:="Warranty job?  Please enter Y or N", Type:=2)
            Application.EnableEvents = True
        End If
    End If
End Sub