上一篇博客《教你快速入门Excel-宏与VBA(上) 》,我们主要对Excel宏与VBA进行了简单的介绍和使用说明,这次我们做一个宏与VBA的简单实例,通过这个实例,了解宏与VBA的优势所在,在此之前,读者有必要了解一下Excel中单元格,行和列的命名和VB的一些基础语法,这里我们不做过多的解释。
需求说明:
某学校要进行体育测试 ,需要根据输入的成绩,自动对应得分,同时自动计算总分,具体表如下:
表一
表二
解决方案:
在表一中输入成绩,自动在表二中查找,该成绩所对应的分数,比如图中张伟的《负重深蹲(次)》项目成绩是40,那么通过查询表二,她的得分应该是97,同时张伟的《负重深蹲(次)》项目得分自动更新为97,对应总分更新为97;
该问题解决依赖简单的录制宏不好实现,这里我们使用VBA编写代码:
模块代码:
点击单元格获取成绩:
Public Sub CellsClick( ByVal Target As Range) If Target.Column < 4 Or Target.Row < 5 Or Target.Column > ActiveSheet.UsedRange.Columns.Count - 1 Or Target.Row > ActiveSheet.UsedRange.Rows.Count Then Exit Sub End If Dim selectedCol As Integer Dim j As Integer Dim isUpdate As Boolean selectedCol = (Target.Column - 4) \ 2 + 2 For j = 2 To Worksheets( "表二" ).UsedRange.Columns.Count Step 1 If Cells(Target.Row, Target.Column).Value <> "" And Cells(Target.Row, Target.Column).Value = Worksheets( "表二" ).Cells(j, selectedCol).Value Then Cells(Target.Row, Target.Column + 1).Value = Worksheets("表二" ).Cells(j, 1).Value isUpdate = True End If Next If Not isUpdate Then Cells(Target.Row, Target.Column + 1).Value = "" End If Dim sum As Double sum = 0 For j = 5 To ActiveSheet.UsedRange.Columns.Count - 3 Step 2 sum = sum + Val(Cells(Target.Row, j).Value) Next Cells(Target.Row, ActiveSheet.UsedRange.Columns.Count - 1).Value = sum End Sub
宏函数:激活时,自动获取全部成绩,也可用于填写成绩自动获得得分,但是由于每次都要激活全部单元格进行刷新,所有如果用此方法解决,则会产生Excel反应慢或是半天没有反应的情况,所以该方法只对应到得分按钮即可,即得分按钮指定宏为Worksheet_Activate!
Public Sub WorksheetActivate() Dim selectedCol As Integer Dim r As Integer Dim c As Integer Dim j As Integer Dim isUpdate As Boolean For r = 5 To ActiveSheet.UsedRange.Rows.Count For c = 4 To ActiveSheet.UsedRange.Columns.Count - 1 Step 2 isUpdate = False selectedCol = (c - 4) \ 2 + 2 For j = 2 To Worksheets( "U15-16女附" ).UsedRange.Rows.Count If Cells(r, c).Value <> "" And Cells(r, c).Value = Worksheets( "表二" ).Cells(j, selectedCol).Value Then Cells(r, c + 1).Value = Worksheets("表二" ).Cells(j, 1).Value isUpdate = True End If Next If Not isUpdate Then Cells(r, c + 1).Value = "" End If Next Next End Sub
表一代码:
Private Sub Worksheet_Change( ByVal Target As Range) If Target.Row = Selection.Row - 1 And Target.Column = Selection.Column Or Target.Row = Selection.Row And Target.Column = Selection.Column - 1 Then CellsClick Target End If End Sub Private Sub Worksheet_SelectionChange( ByVal Target As Range) CellsClick Target End Sub
至此,简单的宏和VBA实例已经讲完了,复杂的问题简单化了吧!所以当你遇到在Excel中需要不断重复一些操作时,就应该考虑使用宏和VBA来解决了,非常方便,更重要的是节省时间呀!
原文来自:http://blog.csdn.net/small_baby01/article/details/22438103