繼續(xù):
'''數(shù)組之應用:Sub MyTestArray() Dim myCrit(1 To 4) As String ' Declaring array and setting bounds Dim Response As String Dim i As Integer Dim myFlag As Boolean myFlag = False
' To fill array with values myCrit(1) = "A" myCrit(2) = "B" myCrit(3) = "C" myCrit(4) = "D"
Do Until myFlag = True Response = InputBox("Please enter your choice: (i.e. A,B,C or D)") ' Check if Response matches anything in array For i = 1 To 4 'UCase ensures that Response and myCrit are the same case If UCase(Response) = UCase(myCrit(i)) Then myFlag = True: Exit For End If Next i Loop End Sub Back
'''替換'// This sub will replace information in all sheets of the workbook \'//...... Replace "old stuff" and "new stuff" with your info ......\Sub ChgInfo() Dim Sht As Worksheet For Each Sht In Worksheets Sht.Cells.Replace What:="old stuff", _ Replacement:="new stuff", LookAt:=xlPart, MatchCase:=False Next End Sub Back
'''改文本為數(shù)值: ' This sub will move the sign from the right-hand side thus changing a text string into a value. Sub MoveMinus() On Error Resume Next Dim cel As Range Dim myVar As Range Set myVar = Selection
For Each cel In myVar If Right((Trim(cel)), 1) = "-" Then cel.Value = cel.Value * 1 End If Next With myVar .NumberFormat = "#,##0.00_);[Red](#,##0.00)" .Columns.AutoFit End With End Sub Back
'''參數(shù)傳輸: ' This sub calls the DetermineUsedRange sub and passes ' the empty argument "usedRng". ''' Sub CallDetermineUsedRange() On Error Resume Next Dim usedRng As Range DetermineUsedRange usedRng MsgBox usedRng.Address End Sub
' This sub receives the empty argument "usedRng" and determines ' the populated cells of the active worksheet, which is stored ' in the variable "theRng", and passed back to the calling sub.
Sub DetermineUsedRange(ByRef theRng As Range) Dim FirstRow As Integer, FirstCol As Integer, _ LastRow As Integer, LastCol As Integer On Error GoTo handleError FirstRow = Cells.Find(What:="*", _ SearchDirection:=xlNext, _ SearchOrder:=xlByRows).Row FirstCol = Cells.Find(What:="*", _ SearchDirection:=xlNext, _ SearchOrder:=xlByColumns).Column LastRow = Cells.Find(What:="*", _ SearchDirection:=xlPrevious, _ SearchOrder:=xlByRows).Row LastCol = Cells.Find(What:="*", _ SearchDirection:=xlPrevious, _ SearchOrder:=xlByColumns).Column Set theRng = Range(Cells(FirstRow, FirstCol), _ Cells(LastRow, LastCol)) handleError: End Sub Back
'Copies only the weekdates from a range of dates. '''從區(qū)域中只復制星期日的數(shù)據(jù):Sub EnterDates() Columns(3).Clear Dim startDate As String, stopDate As String, startCel As Integer, stopCel As Integer, dateRange As Range On Error Resume NextDo startDate = InputBox("Please enter Start Date: Format(mm/dd/yy)", "START DATE") If startDate = "" Then End Loop Until startDate = Format(startDate, "mm/dd/yy") _ Or startDate = Format(startDate, "m/d/yy")Do stopDate = InputBox("Please enter Stop Date: Format(mm/dd/yy)", "STOP DATE") If stopDate = "" Then End Loop Until stopDate = Format(stopDate, "mm/dd/yy") _ Or stopDate = Format(stopDate, "m/d/yy")startDate = Format(startDate, "mm/dd/yy") stopDate = Format(stopDate, "mm/dd/yy")startCel = Sheets(1).Columns(1).Find(startDate, LookIn:=xlValues, lookat:=xlWhole).Row stopCel = Sheets(1).Columns(1).Find(stopDate, LookIn:=xlValues, lookat:=xlWhole).RowOn Error GoTo errorHandlerSet dateRange = Range(Cells(startCel, 1), Cells(stopCel, 1))Call CopyWeekDates(dateRange) ' Passes the argument dateRange to the CopyWeekDates sub.Exit Sub errorHandler: If startCel = 0 Then MsgBox "Start Date is not in table.", 64 If stopCel = 0 Then MsgBox "Stop Date is not in table.", 64 End Sub
Sub CopyWeekDates(myRange) Dim myDay As Variant, cnt As Integer cnt = 1 For Each myDay In myRange If WeekDay(myDay, vbMonday) < 6 Then With Range("C1")(cnt) .NumberFormat = "mm/dd/yy" .Value = myDay End With cnt = cnt + 1 End If Next End Sub Back Microsoft Excel VBA Examples
'''列出公式: Sub ListFormulas() Dim counter As Integer Dim i As Variant Dim sourcerange As Range Dim destrange As Range Set sourcerange = Selection.SpecialCells(xlFormulas) Set destrange = Range("M1") ' Substitute your range here destrange.CurrentRegion.ClearContents destrange.Value = "Address" destrange.Offset(0, 1).Value = "Formula" If Selection.Count > 1 Then For Each i In sourcerange counter = counter + 1 destrange.Offset(counter, 0).Value = i.Address destrange.Offset(counter, 1).Value = "'" & i.Formula Next ElseIf Selection.Count = 1 And Left(Selection.Formula, 1) = "=" Then destrange.Offset(1, 0).Value = Selection.Address destrange.Offset(1, 1).Value = "'" & Selection.Formula Else MsgBox "This cell does not contain a formula" End If destrange.CurrentRegion.EntireColumn.AutoFit End Sub
Sub AddressFormulasMsgBox() 'Displays the address and formula in message box For Each Item In Selection If Mid(Item.Formula, 1, 1) = "=" Then MsgBox "The formula in " & Item.Address(rowAbsolute:=False, _ columnAbsolute:=False) & " is: " & Item.Formula, vbInformation End If Next End Sub Back
'''刪除區(qū)域名:Sub DeleteRangeNames() Dim rName As Name For Each rName In ActiveWorkbook.Names rName.Delete Next rName End Sub Back
'''表格的類型:Sub TypeSheet() MsgBox "This sheet is a " & TypeName(ActiveSheet) End SubBack
'''增加工作表,并檢查已存在的工作表:Sub AddSheetWithNameCheckIfExists() Dim ws As Worksheet Dim newSheetName As String newSheetName = Sheets(1).Range("A1") ' Substitute your range here For Each ws In Worksheets If ws.Name = newSheetName Or newSheetName = "" Or IsNumeric(newSheetName) Then MsgBox "Sheet already exists or name is invalid", vbInformation Exit Sub End If Next Sheets.Add Type:="Worksheet" With ActiveSheet .Move after:=Worksheets(Worksheets.Count) .Name = newSheetName End With End Sub
'''增加工作表:Sub Add_Sheet() Dim wSht As Worksheet Dim shtName As String shtName = Format(Now, "mmmm_yyyy") For Each wSht In Worksheets If wSht.Name = shtName Then MsgBox "Sheet already exists...Make necessary " & _ "corrections and try again." Exit Sub End If Next wSht Sheets.Add.Name = shtName Sheets(shtName).Move After:=Sheets(Sheets.Count) Sheets("Sheet1").Range("A1:A5").Copy _ Sheets(shtName).Range("A1") End Sub
'''復制工作表:Sub Copy_Sheet() Dim wSht As Worksheet Dim shtName As String shtName = "NewSheet" For Each wSht In Worksheets If wSht.Name = shtName Then MsgBox "Sheet already exists...Make necessary " & _ "corrections and try again." Exit Sub End If Next wSht Sheets(1).Copy before:=Sheets(1) Sheets(1).Name = shtName Sheets(shtName).Move After:=Sheets(Sheets.Count) End Sub Back
'''初始化,賦予0值:Sub ResetValuesToZero2() For Each n In Worksheets("Sheet1").Range("WorkArea1") ' Substitute your information here If n.Value <> 0 Then n.Value = 0 End If Next n End Sub
'''置0: Sub ResetTest1() For Each n In Range("B1:G13") ' Substitute your range here If n.Value <> 0 Then n.Value = 0 End If Next n End Sub
'''是數(shù)字都置0: Sub ResetTest2() For Each n In Range("A16:G28") ' Substitute your range here If IsNumeric(n) Then n.Value = 0 End If Next n End Sub
'''置0: Sub ResetTest3() For Each amount In Range("I1:I13") ' Substitute your range here If amount.Value <> 0 Then amount.Value = 0 End If Next amount End Sub
'''置0: Sub ResetTest4() For Each n In ActiveSheet.UsedRange If n.Value <> 0 Then n.Value = 0 End If Next n End Sub
'''初始化值:Sub ResetValues() On Error GoTo ErrorHandler For Each n In ActiveSheet.UsedRange If n.Value <> 0 Then n.Value = 0 End If TypeMismatch: Next n ErrorHandler: If Err = 13 Then 'Type Mismatch Resume TypeMismatch End If End Sub
'''初始化值:
Sub ResetValues2() For i = 1 To Worksheets.Count On Error GoTo ErrorHandler For Each n In Worksheets(i).UsedRange If IsNumeric(n) Then If n.Value <> 0 Then n.Value = 0 ProtectedCell: End If End If Next n ErrorHandler: If Err = 1005 Then Resume ProtectedCell End If Next i End Sub Back
'''計算報酬:Sub CalcPay() On Error GoTo HandleError Dim hours Dim hourlyPay Dim payPerWeek hours = InputBox("Please enter number of hours worked", "Hours Worked") hourlyPay = InputBox("Please enter hourly pay", "Pay Rate") payPerWeek = CCur(hours * hourlyPay) MsgBox "Pay is: " & Format(payPerWeek, "$##,##0.00"), , "Total Pay" HandleError: End Sub Back
'''打印: 'To print header, control the font and to pull second line of header (the date) from worksheet Sub Printr() ActiveSheet.PageSetup.CenterHeader = "&""Arial,Bold Italic""&14My Report" & Chr(13) _ & Sheets(1).Range("A1") ActiveWindow.SelectedSheets.PrintOut Copies:=1 End Sub
Sub PrintRpt1() 'To control orientation Sheets(1).PageSetup.Orientation = xlLandscape Range("Report").PrintOut Copies:=1 End Sub
Sub PrintRpt2() 'To print several ranges on the same sheet - 1 copy Range("HVIII_3A2").PrintOut Range("BVIII_3").PrintOut Range("BVIII_4A").PrintOut Range("HVIII_4A2").PrintOut Range("BVIII_5A").PrintOut Range("BVIII_5B2").PrintOut Range("HVIII_5A2").PrintOut Range("HVIII_5B2").PrintOut End Sub
'To print a defined area, center horizontally, with 2 rows as titles, 'in portrait orientation and fitted to page wide and tall - 1 copy Sub PrintRpt3() With Worksheets("Sheet1").PageSetup .CenterHorizontally = True .PrintArea = "$A$3:$F$15" .PrintTitleRows = ("$A$1:$A$2") .Orientation = xlPortrait .FitToPagesWide = 1 .FitToPagesTall = 1 End With Worksheets("Sheet1").PrintOut End Sub Back
' This is a simple example of using the OnEntry property. The Auto_Open sub calls the Action ' sub.The font is set to bold in the ActiveCell if the value is >= 500. Thus if the value is >=500, ' then ActiveCell.Font.Bold = True. If the value is less than 500, then ActiveCell.Font.Bold = False.
' The Auto_Close sub "turns off" OnEntry. Sub Auto_Open() ActiveSheet.OnEntry = "Action" End Sub
Sub Action() If IsNumeric(ActiveCell) Then ActiveCell.Font.Bold = ActiveCell.Value >= 500 End If End Sub Sub Auto_Close() ActiveSheet.OnEntry = "" End Sub Back
'These subs place the value (result) of a formula into a cell rather than the formula. '''捷徑:Sub GetSum() ' using the shortcut approach [A1].Value = Application.Sum([E1:E15]) End Sub
Sub EnterChoice() Dim DBoxPick As Integer Dim InputRng As Range Dim cel As Range DBoxPick = DialogSheets(1).ListBoxes(1).Value Set InputRng = Columns(1).Rows
For Each cel In InputRng If cel.Value = "" Then cel.Value = Application.Index([InputData!StateList], DBoxPick, 1) End End If Next
End Sub Back
'''把名字送給已知的區(qū)域: ' To add a range name for known range Sub AddName1() ActiveSheet.Names.Add Name:="MyRange1", RefersT="=$A$1:$B$10" End Sub
'''把名字送給已選中的區(qū)域: ' To add a range name based on a selection Sub AddName2() ActiveSheet.Names.Add Name:="MyRange2", RefersT="=" & Selection.Address() End Sub
'''把名字送給已選中的區(qū)域: ' To add a range name based on a selection using a variable. Note: This is a shorter version Sub AddName3() Dim rngSelect As String rngSelect = Selection.Address ActiveSheet.Names.Add Name:="MyRange3", RefersT="=" & rngSelect End Sub
'''為選中的區(qū)域取名: ' To add a range name based on a selection. (The shortest version) Sub AddName4() Selection.Name = "MyRange4" End Sub Back
Microsoft Excel VBA Examples
Events
'''事件:
The code for a sheet event is located in, or is called by, a procedure in the code section of the worksheet. Events that apply to the whole workbook are located in the code section of ThisWorkbook. Events are recursive. That is, if you use a Change Event and then change the contents of a cell with your code, this will innate another Change Event, and so on, depending on the code. To prevent this from happening, use: Application.EnableEvents = False at the start of your code Application.EnabeEvents = True at the end of your code
' This is a simple sub that changes what you type in a cell to upper case. Private Sub Worksheet_Change(ByVal Target As Excel.Range) Application.EnableEvents = False Target = UCase(Target) Application.EnableEvents = True End Sub
' This sub shows a UserForm if the user selects any cell in myRange Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range) On Error Resume Next Set myRange = Intersect(Range("A1:A10"), Target) If Not myRange Is Nothing Then UserForm1.Show End If End Sub
' You should probably use this with the sub above to ensure ' that the user is outside of myRange when the sheet is activated. Private Sub Worksheet_Activate() Range("B1").Select End Sub
' In this example, Sheets("Table") contains, in Column A, a list of ' dates (for example Mar-97) and in Column B, an amount for Mar-97. ' If you enter Mar-97 in Sheet1, it places the amount for March in ' the cell to the right. (The sub below is in the code section of ' Sheet 1.)
Private Sub Worksheet_Change(ByVal Target As Excel.Range) On Error GoTo iQuitz Dim cel As Range, tblRange As Range Set tblRange = Sheets("Table").Range("A1:A48") Application.EnableEvents = False For Each cel In tblRange If UCase(cel) = UCase(Target) Then With Target(1, 2) .Value = cel(1, 2).Value .NumberFormat = "#,##0.00_);[Red](#,##0.00)" End With Columns(Target(1, 2).Column).AutoFit Exit For End If Next iQuitz: Application.EnableEvents = True End Sub
'If you select a cell in a column that contains values, the total 'of all the values in the column will show in the statusbar.
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range) Dim myVar As Double myVar = Application.Sum(Columns(Target.Column)) If myVar <> 0 Then Application.StatusBar = Format(myVar, "###,###") Else Application.StatusBar = False End If End Sub More to come ....... I have just started this page. Back |