本文介绍的VBA程序是一个自定义函数,整理自jkp-ads.com,很好地增强了内置的CallByName函数的适用性。
该函数接受单元格对象、代表该对象属性的字符串和属性值作为参数,返回满足属性值的所有单元格。程序代码如下:
Function FindCells(ByRefoRange As Range, ByVal sProperties As String, _
ByVal vValue As Variant) As Range
Dim oResultRange As Range
Dim oArea As Range
Dim oCell As Range
Dim bDoneOne As Boolean
Dim oTemp As Object
Dim lCount As Long
Dim lProps As Long
Dim vProps As Variant
vProps = Split(sProperties, ".")
lProps = UBound(vProps)
For Each oArea In oRange.Areas
For Each oCell In oArea.Cells
Set oTemp = oCell
For lCount = 0 To lProps - 1
Set oTemp = CallByName(oTemp,vProps(lCount), VbGet)
Next
If CallByName(oTemp,vProps(lProps), VbGet) = vValue Then
If bDoneOne Then
Set oResultRange =Union(oResultRange, oCell)
Else
Set oResultRange = oCell
bDoneOne = True
End If
End If
Next
Next
If Not oResultRange Is Nothing Then
Set FindCells = oResultRange
End If
End Function
假设有如下图1所示的工作表,其中有黄色和红色背景色的单元格。
图1
下面使用FindCells函数查找并选择所有红色背景色的单元格,代码如下:
Sub UseFindCellsExample()
FindCells(ActiveSheet.UsedRange,"Interior.ColorIndex", 3).Select
End Sub
代码中,传递的单元格对象为当前工作表中已使用的区域、属性为单元格背景色、属性值为3(即红色)。运行代码后的结果如下图2所示。
图2
在代码中,我们使用了CallByName函数来增强其适应性。CallByName函数的语法为:
CallByName(object, procname,calltype, [args()])
其中:
1.参数object,必需,Variant型(Object),在函数中执行的对象的名称。
2.参数procname,必需,Variant型(String),代表对象的属性或方法名的字符串。
3.参数calltype,必需,一个vbCallType型的常量,代表被调用的过程的类型,可以是vbGet(返回属性)、vbLet(修改属性)、vbMethod(执行方法)、vbSet(设置对象)。
4.参数args(),可选,Variant型(数组)。
例如,如果想获取上图1所示的工作表单元格A2的背景色的值,可以使用下面的代码:
Sub test()
MsgBox CallByName(ActiveCell.Interior,"Colorindex", VbGet)
End Sub
返回值6,是代表黄色的颜色值。
然而,如果想要在CallByName函数中使用下面更通用一些的代码:
Sub test()
MsgBox CallByName(ActiveCell, "Interior.Colorindex", VbGet)
EndSub
会返回错误,因为参数procname仅接受单个的条目,这就需要使用我们在前面的自定义函数FindCells,将其拆分成单个的元素。
欢迎在下面留言,完善本文内容,让更多的人学到更完美的知识。