VB调用excel函数WorksheetFunction
(2020-08-21 21:12:30)
标签:
it |
分类: office技巧 |
ActiveCell.FormulaR1C1
= Application.WorksheetFunction.Sum(Range("k1:k"
& Cells(hs, 6).Row))
需要注意的是函数里面的变量需要单独按照VBA定义,如果写Application.WorksheetFunction.Sum(K1:K8)
无法输出结果
2)表中使用函数和规则和VBA中使用函数的语法规则不一样。比如单元格中,求和函数sum(A1:A3),在VBA中,通过application或worksheetfunction的调用时就和函数是sum(range(“A1:A3"))。这里,"A1:A3"字符串变为range的一个参数,而range()作为sum的参数。如果是某个一个单元格,也可以用cell(行号,列号)替代range()。值得注意的是,使用cells()时,其行号和列号全部可变为变量,而用range()参数为字符串,如果涉及变量,就需要进行字符串组合的方式使之变为一个区域参数。当然,range()参数的字符串也可以通过cells替换,比如range(“A1:B4”)通过range(cells(1,1),cells(4,2))
3)调用函数可以逐级调用。首先是application,其次是worksheetfunction,最后是application.worksheetfunction方式。
示例
Sub 宏1()
'
' 宏1 宏
'
Dim i, rag1 As Range,
aRow%
profit = 0
Set rag1 =
Sheets("sheet2").Range("F1:F8000")
aRow =
Application.WorksheetFunction.Count(rag1)
Sheets("sheet1").Range("E8") =
aRow
aRow =
Application.WorksheetFunction.Count(Sheets("sheet2").Range("F1:F8000"))
Sheets("sheet1").Range("E9") =
aRow
aRow =
Sheets("sheet2").Range("F65536").End(xlUp).Row
For Each i In
Sheets("sheet2").Range("F1:F" & aRow)
If i.Interior.ColorIndex =
Sheets("sheet1").Range("D4").Interior.ColorIndex Then
profit = profit +
i.Value
End If
Next
Sheets("sheet1").Range("E4") =
profit
End Sub