MyColumn=Target.Column 获取活动单元格所在的列号
MyRow=Target.Row 获取活动单元格所在的行号
工作表名.UsedRange.Rows.Count 指定工作表已使用的行的总数
工作表名.UsedRange.Columns.Count 指定工作表已使用的列的总数
工作表名.Cells(行号, 列号).Value 获取指定工作表某个单元格的值
Worksheets(m).Cells(i, j).Value 使用通用的序号方法,调用某个工作表的某个单元格的数据
for i=1 to Worksheets.Count 循环当前工作薄的每一个工作表
下面来一段如上代码的综合使用:
If (Target.Column = 1) Then
For j = 1 To Sheet2.UsedRange.Rows.Count
If (Trim(Sheet1.Cells(Target.Row, 1).Value) = Trim(Sheet2.Cells(j, 1).Value)) Then
Sheet1.Cells(Target.Row, 2).Value = Sheet2.Cells(j, 2).Value
End If
Next j
End If
如下的代码,是在VBA环境下调用Excel的函数。
Worksheets(1).Range(Cells(6, 1), Cells(6, 1)) = Application.WorksheetFunction.Sum(Range(Cells(1, 1), Cells(4, 2)))
Worksheets(1).Range(Cells(6, 2), Cells(6, 2)) = Application.WorksheetFunction.Average(Worksheets(1).Range(Cells(1, 1), Cells(4, 2))) 最好的调用方法了
Worksheets(1).Range("C6") = Application.Max(Worksheets("Sheet1").Range("A1:B4"))
Worksheets(1).Range("D6") = Application.Min(Range("A1:B4"))
Worksheets("sheet1").Range("E6") = WorksheetFunction.Median(Range("A1:B4"))
再来一下特殊的代码:
Excel检查用户按了F1或F3,自动执行某过程的代码
Application.OnKey key:="{F1}", procedure:="MyAutoInput1"
Application.OnKey key:="{F3}", procedure:="MyAutoInput2"
下面是完整的代码:
Private Sub Workbook_Open()
Application.OnKey key:="{F1}", procedure:="MyAutoInput1"
Application.OnKey key:="{F3}", procedure:="MyAutoInput2"
End Sub
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
MyRow = Target.Row
End Sub
Public MyRow As Integer
Sub MyAutoInput1()
ActiveSheet.Cells(MyRow, 4).Value = 200
End Sub
Sub MyAutoInput2()
ActiveSheet.Cells(MyRow, 4).Value = 300
End Sub
最后,再贴上一组代码,分别返回Excel文件所在的路径,注意,返回的路径方式是不一样的:
MsgBox Application.Path
ActiveSheet.Cells(1, 1).Value = Application.Path
MsgBox ThisWorkbook.Path
ActiveSheet.Cells(2, 1).Value = ThisWorkbook.Path
MsgBox Application.DefaultFilePath
ActiveSheet.Cells(3, 1).Value = Application.DefaultFilePath
MsgBox Application.ActiveWorkbook.Path
ActiveSheet.Cells(4, 1).Value = Application.ActiveWorkbook.Path
MsgBox Application.ActiveWorkbook.FullName
ActiveSheet.Cells(5, 1).Value = Application.ActiveWorkbook.FullName
MsgBox Application.ActiveWorkbook.Name
ActiveSheet.Cells(6, 1).Value = Application.ActiveWorkbook.Name
如上的代码够经典了,适合擅长于使用智能化的通用的代码的学习者使用。以后有时间有机会,再给大家贴出更多的代码。
新闻热点
疑难解答