![](/img/trans.png)
[英]Excel 2010 vba Can I reference the result of a worksheetfunction in another formula?
[英]Excel - VBA: WorksheetFunction and variable in one formula
我在Excel中具有下面的VBA代碼,但我不斷收到以下錯誤: Run-time error '13': Type mismatch.
這是代碼,
Dim ssw
Dim ave
Dim mdq
Dim rec
ssw = Cells(2, 2).Value
mdq = Cells(3, 2).Value
Sheets("Sum").Select
rec = WorksheetFunction.Count(Range(Cells(2, 1), Cells(500000, 1)))
For i = 2 To rec + 1
ave = WorksheetFunction.AverageIf(Range(Cells(2, 1), Cells(rec + 1, 1)), Cells(i, 1).Value, Range(Cells(2, 7), Cells(rec + 1, 7)))
Cells(i, 9).Value = ave * ssw
Next i
從我所看到的,我不能像我的代碼中那樣將變量與工作表函數相乘。 我可以以某種方式轉換工作表函數結果或變量ssw
以便我可以將兩者相乘。 我還考慮了將實際公式放入單元格中,但我並不是真的想要那樣。
我不知道為什么您添加了rec + 1,這可能是您收到錯誤的原因。 嘗試這個
Dim ssw
Dim ave
Dim mdq
Dim rec
ssw = Cells(2, 2).Value
mdq = Cells(3, 2).Value
Sheets("Sum").Select
rec = WorksheetFunction.Count(Range(Cells(2, 1), Cells(500000, 1)))
For i = 2 To rec
ave = WorksheetFunction.AverageIf(Range(Cells(2, 1), Cells(rec , 1)), Cells(i, 1).Value, Range(Cells(2, 7), Cells(rec, 7)))
Cells(i, 9).Value = ave * ssw
Next i
我找到了解決問題的辦法。 我擁有的代碼是用於名為Inputs的工作表上的一個按鈕的,而結果則放在另一個名為Sum的工作表中。 當我測試代碼時,我從VBA IDE中運行/調試了它,這給了我錯誤,但是當我進入輸入表並按下按鈕時,它可以正常工作。 但是我所做的是將Sheets("Inputs").Select
在變量之后的代碼中Sheets("Inputs").Select
。 現在的代碼看起來像這樣,
Dim ssw
Dim ave
Dim mdq
Dim rec
Sheets("Inputs").Select
ssw = Cells(2, 2).Value 'These two cells are from the Inputs sheet
mdq = Cells(3, 2).Value
Sheets("Sum").Select
' From here all the cells refer to the Sum sheet
rec = WorksheetFunction.Count(Range(Cells(2, 1), Cells(500000, 1)))
For i = 2 To rec + 1
ave = WorksheetFunction.AverageIf(Range(Cells(2, 1), Cells(rec + 1, 1)), Cells(i, 1).Value, Range(Cells(2, 7), Cells(rec + 1, 7)))
Cells(i, 9).Value = ave * ssw
Next i
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.