Monday 28 December 2009

在Excel中根据背景颜色来计算数据

第一次用Excel的宏,挺好玩。找了点资料。

原帖在 http://club.excelhome.net/viewthread.php?tid=81978&extra=&page=3

也有代码下载,我就不提供了。

我用的版本是03


步骤:

1.打开Excel, Alt+F11 打开VBA宏编辑器,新建一个模块,并在里面定义一个VBA函数。

代码
Function Countcolor(col As Range, countrange As Range)
 
Dim icell As Range
 Application.Volatile
 
For Each icell In countrange
     
If icell.Interior.ColorIndex = col.Interior.ColorIndex Then
         Countcolor 
= Countcolor + 1
     
End If
 
Next icell
End Function

2.该函数有2个参数,Para1的作用是做为背景颜色来比对,而Para2是统计的区域。

3.在Excel Sheet Cell中引用

=Countcolor(B$1,$A$1:$A$65535)

 

注意事项:

1. 如果不能运行,请查看宏的安全设置:工具->选项->安全->将安全级别降到中。

2.在VBA宏中,有Excel对象和模块定义。该函数需要在模块中定义,否则不能运行。因为带定义的需要在模块中才能定义。

No comments: