VBA乘以两个命名范围

时间:2016-06-13 13:02:11

标签: excel vba variables range

我一直试图在各处查看,我似乎无法找到答案或让它发挥作用。

我有代码

'Define Variables for cell ranges'
Dim BidItem As Range
Dim BidItemDes As Range
Dim BidItemUnit As Range
Dim BidItemQTY As Range
Dim BidItemUP As Range

'Store the sheet range into the variables'
Set BidItem = Sheets("BidItems").Range("A1:A" & Range("A1").End(xlDown).Row)
Set BidItemDes = Sheets("BidItems").Range("B1:B" & Range("B1").End(xlDown).Row)
Set BidItemUnit = Sheets("BidItems").Range("C1:C" & Range("C1").End(xlDown).Row)
Set BidItemQTY = Sheets("BidItems").Range("D1:D" & Range("D1").End(xlDown).Row)       
Set BidItemUP = Sheets("BidItems").Range("E1:E" & Range("E1").End(xlDown).Row)
Set BidItemValue = Sheets("BidItems").Range("F1:F" & Range("F1").End(xlDown).Row)

Set BidItemValue = Sheets("BidItems").Range("F1:F" & Range("F1").End(xlDown).Row)

我需要做的是将所有数据放在BidItemQTY范围内,并将其乘以BidItemUP范围 然后将该答案输出到BidItemValue范围。

我有最后一行代码设置来启动该功能但是 我似乎无法掌握如何使用变量在VBA中执行数学函数。

1 个答案:

答案 0 :(得分:2)

考虑这个小例子:

Sub dural()
    Dim second As Range
    Dim first As Range, prodt As Long

    Set first = Range("A1:A3")
    Set second = Range("B1:B3")
    prodt = Application.WorksheetFunction.SumProduct(first, second)

    MsgBox prodt
End Sub

enter image description here

修改#1:

要将单个产品存储在单元格中,请使用:

Sub dural()
    Dim second As Range
    Dim first As Range, prodt As Long
    Dim third As Range

    Set first = Range("A1:A3")
    Set second = Range("B1:B3")
    Set third = Range("C1:C3")

    For i = 1 To 3
        third(i, 1) = first(i, 1) * second(i, 1)
    Next i

End Sub

enter image description here

<强> 注意:

  • 由于范围不是单个单元格,我们将它们视为二维
  • 可以使用 Transpose()
  • 来避免循环
  • 在这种情况下,一维也会起作用:


For i = 1 To 3
        third(i) = first(i) * second(i)
Next i