打开基于Checkbox的InputBox

时间:2017-10-24 15:03:40

标签: excel-vba checkbox inputbox vba excel

我不熟悉Excel VBA所以,如果这听起来像是一个明显的问题,请道歉...... 我正在Excel中构建模型,如果选中inputbox,我实际上是尝试触发checkbox

到目前为止,我设法做了以下事情:

Private Sub Worksheet_Change(ByVal Target As Range)
    Set Target = Range("G7")

    If Target.Value = "TRUE" Then

        Dim QtyEntry As Integer
        Dim Msg As String
        Msg = "Please insert value"
        QtyEntry = InputBox(Msg)
        ActiveSheet.Range("C7").Value = QtyEntry / 100

    End If
End Sub

target.value G7是与checkbox关联的单元格,因此当检查开启时会返回TRUE,或者当检查关闭时会返回FALSE 。 但是,我有两种问题。第一个是当我选中复选框时宏实际上没有激活(但如果我在目标单元格中​​写“TRUE”,它就会激活。

第二个是当inputbox出现时,它正确地将值放在单元格C7中,但随后它继续要求输入值而不会消失。

1 个答案:

答案 0 :(得分:1)

为什么不直接拿这样的复选框事件呢?

Private Sub CheckBox1_Change()
    If (CheckBox1.Value) Then

        Dim QtyEntry As Integer
        Dim Msg As String
        Msg = "Please insert value"

        'errNum is used to catch if an error has happened from the inputbox entry
        Dim errNum as integer
        Err.Clear
        On error resume next 'this line tells the code to continue even if it encounters an error
        QtyEntry = InputBox(Msg)
        errNum = Err.Number
        On error goto 0 'this reset the default behavior of error handling

        Excel.Application.enableEvents = False 'this is to avoid the change of the cell "C7" calling your `Worksheet_Change` event
        'edit to include if user click cancel or nothing is entered
        If (errNum = 0) then
           ActiveSheet.Range("C7").Value = QtyEntry / 100
        End if
        Excel.Application.enableEvents = True

    End If
End Sub

与ActiveX Checkbox

一起使用