传递InputBox条目会生成运行时错误' 424':需要对象

时间:2014-06-24 14:14:30

标签: excel excel-vba vba

输入框输入项目名称,例如“测试项目”。然后出现另一个输入框输入成本,例如“13.2”。该代码旨在查找B列中的第一个空单元格并输入Item,然后向右偏移一列并输入Cost。

我收到运行时错误'424':

上需要对象

ActiveCell.Offset(1,0).Select.FormulaR1C1 = Item

  Sub AddSWItem()
      Dim Item As String
      Dim Cost As String

      Item = InputBox("Item")
      Cost = InputBox("Cost")

      Range("B11").Select
      Selection.End(xlDown).Select
      ActiveCell.Offset(1, 0).Select
      ActiveCell.FormulaR1C1 = Item
      ActiveCell.Offset(0, 2).Select
      ActiveCell.FormulaR1C1 = Cost
  End Sub

1 个答案:

答案 0 :(得分:2)

我猜你想出了你想要的东西,但这里有关于替代编码的一些注释。

使用VBA,您可以直接寻址细胞而不使用活动细胞。当您希望用户定义结果的放置位置时,活动单元格非常有用。如果已知位置,则可以使用Range对象。

以下是几个例子。还包括一些标准的VBA错误逻辑和调试技术。

        Sub AddSWItem()
        On Error GoTo Local_err
            Dim Item As String
            Dim Cost As String
            Dim rng As Range

            Item = InputBox("Item")
            Cost = InputBox("Cost")

            ' QA code here

            Set rng = Range("B11")
            rng(1, 0) = Item
            rng(0, 2) = Cost

            ' or use direct entry

            rng(2, 0) = InputBox("Item 2")
            rng(1, 2) = InputBox("Cost 2")

            ' or

            Range("B11")(3, 0) = InputBox("Item 3")
            Range("B11")(2, 2) = InputBox("Cost 3")

       Local_Exit:
            Exit Sub
       Local_err:
            MsgBox Err & " " & Err.Description
            Resume Local_err ' Ctrl-Break to debug at this point
            Resume ' Right click -set next statement here to resume on failed line
        End Sub