萬盛學電腦網

 萬盛學電腦網 >> Excel教程 >> excel綜合 >> vba操作Excel經典的通用的代碼之一

vba操作Excel經典的通用的代碼之一

   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

  如上的代碼夠經典了,適合擅長於使用智能化的通用的代碼的學習者使用。以後有時間有機會,再給大家貼出更多的代碼。

copyright © 萬盛學電腦網 all rights reserved