簡體   English   中英

將 Excel 公式轉換為 VBA

[英]Convert Excel Formula to VBA

我有這個公式,它查看跨多列的各種條件,並檢查是否所有條件都匹配,它會將數據從一列粘貼到另一列。 我已經嘗試了幾種方法將其導入 VBA,但似乎無法正常工作。 謝謝!

=INDEX($D$2:$D$1112,MATCH(1,($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3),0))

您將無法使用該數組公式直接將值返回到單元格。 VBA 不會像工作表那樣處理數組公式。 最好的方法是使用工作表的處理或 應用程序評估方法之一。

您缺少可供參考的工作表讓我很煩惱。 當公式位於工作表單元格中時,它知道它在哪個工作表上。 在 VBA 中使用公式時,父工作表是沒有明確工作表引用的“最佳猜測”。

以下是將數組公式的結果放入活動工作表上的 Z2:Z4 的三種方法。 請記住,應修改這些單元格引用以包含工作表名稱。

With ActiveSheet
    'this simply puts the formula into the worksheet then reverts the cell from the formula to the returned formula value
    .Range("Z2").FormulaArray = "=INDEX($D$2:$D$1112, MATCH(1, ($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3), 0))"
    .Range("Z2") = .Range("Z2").Value

    'this uses the 'square bracket' method of evaluating a formula on-the-fly
    'the formula being evaluated can be array or non-array
    'this method is does not like building a formula string from pieces of text
    .Range("Z3") = [INDEX($D$2:$D$1112, MATCH(1, ($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3), 0))]

    'similar to the method directly above, Application.Evaluate does just that.
    'the formula being evaluated can be array or non-array
    'this method is easier to build a formula string from pieces of text
    .Range("Z4") = Application.Evaluate("INDEX($D$2:$D$1112, MATCH(1, ($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3), 0))")
End With

您需要進行 2 次更改:

(1) 要在本地 Excel 中可用的 VBA 中使用函數,您需要在每個函數前加上 Application.WorksheetFunction。 IE:

x = Application.WorksheetFunction.Sum(y,z)

(2) 要引用工作表中的單元格,在 VBA 中,您需要通過以下幾種方式之一專門訪問它。 對我們而言,最簡單的是 RANGE 屬性,如下所示:

x = Application.WorksheetFunction.Sum(Range("A1:A2"))

因此,要將這兩個更改放在一起,您的公式將如下所示:

=Application.WorksheetFunction.INDEX(Range("$D$2:$D$1112",Application.WorksheetFunction.MATCH(1,(RANGE("$A$2:$A$1112"=RANGE("$U$7")*(Range("$C$2:$C$1112"=Range("$W$7")*(Range("$B$2:$B$1112"=Range("F3"),0))

雖然我現在看到你似乎在使用數組公式 - 不確定是否需要任何特殊的夾具才能使其工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM