尝试将子过程应用于表中的两列

时间:2019-06-11 14:57:37

标签: excel vba

我是VBA的新手,我想边走边学。我目前有一张数据表,其中一列是单位,一列是UnitCost,而我想填充的不存在的列是Total。我想使用UnitCost的多个Unit填充Total中的每一行。当我尝试运行以下代码块时,出现以下错误消息:“对象变量或未设置块变量”

这是我的代码:

Private Sub CommandButton7_Click()
Dim Units As Range, UnitCost As Range, Total As Range
Units = Worksheets("Sheet1").Range("E2:E44").Value
UnitCost = Worksheets("Sheet1").Range("F2:F44").Value
Total = Units * UnitCost
Range("H2:H44").Value = Total
End Sub

我不确定是否需要更改数据类型(从范围更改为两倍)? 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您需要弄清一些事情。除了上面@Damian的注释之外,您似乎还试图将基于内存的数组与范围一起使用。很好,但是您没有区分哪个是Range和哪个数组。然后,您尝试使用Total = Units * UnitCost将两个范围(或数组)相乘。这也不行。

此示例代码向您展示如何清楚地定义您正在使用的变量以及 如何 。记住要always use Option Explicit

Option Explicit

Private Sub CommandButton7_Click()
    Dim unitsArea As Range
    Dim unitsData As Variant
    Set unitsArea = Sheet1.Range("E2:E44")
    unitsData = unitsArea

    Dim unitCostArea As Range
    Dim unitCostData As Variant
    Set unitCostArea = Sheet1.Range("F2:F44")
    unitCostData = unitCostArea

    '--- create an array for results the same size as the inputs
    Dim totals As Variant
    ReDim totals(LBound(unitsData) To UBound(unitsData), 1 To 1)

    Dim i As Long
    For i = LBound(totals) To UBound(totals)
        totals(i, 1) = unitsData(i, 1) * unitCostData(i, 1)
    Next i

    '--- finally copy the results back to the worksheet
    Dim totalsArea As Range
    Set totalsArea = Sheet1.Range("H2:H44")
    totalsArea = totals
End Sub