2016-06-13 130 views
1

我一直在試圖查找這個地方,我似乎無法找到答案或讓它工作。VBA乘以兩個命名範圍

我的代碼

'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的所有數據,並通過回答範圍BidItemValue範圍BidItemUP ,然後輸出相乘。

我有最後一行代碼設置來啓動功能,但 我似乎無法掌握如何在VBA中使用變量來進行數學函數。

+0

難道你不能在列F中手動添加公式並向下拖動? '= $ D1 * $ E1' –

回答

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

注:

  • 由於範圍不是單細胞,我們把它們當作二維
  • 有可能避免使用移調()的循環
  • 在這種情況下,一維也將工作:


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

看着Dans代碼我以爲他希望每個項目都有一個單獨的值,因爲'BidItemValue'變量覆蓋了F列中的許多單元格。我可能是錯的,但在這種情況下SUMPRODUCT絕對是答案。 –

+0

是的,我正在尋找它自己添加每一行的IE瀏覽器:F2 = D2 * E2,F3 = D3 * E3等 –

+0

@DanLopes看我**編輯#1:** –