Sub AddSerialNumbers() Dim i AsInteger OnErrorGoTo Last i = InputBox("Enter Value", "Enter Serial Numbers") For i = 1To i ActiveCell.Value = i ActiveCell.Offset(1, 0).Activate Next i Last:ExitSub EndSub
Sub InsertMultipleColumns() Dim i AsInteger Dim j AsInteger ActiveCell.EntireColumn.Select OnErrorGoTo Last i = InputBox("Enter number of columns to insert", "Insert Columns") For j = 1To i Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromRightorAbove Next j Last: ExitSub EndSub'Translate By Tmtony
Sub InsertMultipleRows() Dim i AsInteger Dim j AsInteger ActiveCell.EntireRow.Select OnErrorGoTo Last i = InputBox("Enter number of columns to insert", "Insert Columns") For j = 1To i Selection.Insert Shift:=xlToDown, CopyOrigin:=xlFormatFromRightorAbove Next j Last: ExitSub EndSub
Sub DateInHeader() With ActiveSheet.PageSetup .LeftHeader = "" .CenterHeader = "&D" .RightHeader = "" .LeftFooter = "" .CenterFooter = "" .RightFooter = "" End With End Sub
此宏在运行标头时向其添加日期。它只是使用标签”
10. 自定义页眉/页脚
1 2 3 4 5 6 7 8 9 10 11 12
Sub CustomHeader() Dim myText AsString myText = InputBox("Enter your text here", "Enter Text") With ActiveSheet.PageSetup .LeftHeader = "" .CenterHeader = myText .RightHeader = "" .LeftFooter = "" .CenterFooter = "" .RightFooter = "" EndWith EndSub
Sub HighlightRanges() Dim RangeName As Name Dim HighlightRange As Range OnErrorResumeNext ForEach RangeName In ActiveWorkbook.Names Set HighlightRange = RangeName.RefersToRange HighlightRange.Interior.ColorIndex = 36 Next RangeName EndSub
Sub highlightValue() Dim myStr AsString Dim myRg As range Dim myTxt AsString Dim myCell As range Dim myChar AsString Dim I AsLong Dim J AsLong OnErrorResumeNext If ActiveWindow.RangeSelection.Count > 1Then myTxt = ActiveWindow.RangeSelection.AddressLocal Else myTxt = ActiveSheet.UsedRange.AddressLocal EndIf LInput: Set myRg = _ Application.InputBox _ ("please select the data range:", "Selection Required", myTxt, , , , , 8) If myRg IsNothingThenExitSub If myRg.Areas.Count > 1Then MsgBox "not support multiple columns" GoTo Linput EndIf If myRg.Columns.Count <> 2Then MsgBox "the selected range can only contain two columns " GoTo Linput EndIf For I = 0To myRg.Rows.Count - 1 myStr = myRg.range("B1").Offset(I, 0).Value With myRg.range("A1").Offset(I, 0) .Font.ColorIndex = 1 For J = 1To Len(.Text) Mid(.Text, J, Len(myStr)) = myStrThen .Characters(J, Len(myStr)).Font.ColorIndex = 3 Next EndWith Next I EndSub
Sub highlightErrors() Dim rng As Range Dim i AsInteger ForEach rng In ActiveSheet.UsedRange If WorksheetFunction.IsError(rng) Then i = i + 1 rng.Style = "bad" EndIf Next rng MsgBox _ "There are total " & i _ & " error(s) in this worksheet." EndSub'Translate By Tmtony
Sub highlightSpecificValues() Dim rng As range Dim i As Integer Dim c As Variant c = InputBox("Enter Value To Highlight") ForEach rng In ActiveSheet.UsedRange If rng = c Then rng.Style = "Note" i = i + 1 EndIf Next rng MsgBox "There are total " & i & " " & c & " in this worksheet." EndSub
Sub highlightUniqueValues() Dim rng As Range Set rng = Selection rng.FormatConditions.Delete Dim uv As UniqueValues Set uv = rng.FormatConditions.AddUniqueValues uv.DupeUnique = xlUnique uv.Interior.Color = vbGreen EndSub'Translate By Tmtony
Sub ProtectAllWorskeets() Dim ws As Worksheet Dim ps AsString ps = InputBox("Enter a Password.", vbOKCancel) ForEach ws In ActiveWorkbook.Worksheets ws.Protect Password:=ps Next ws EndSub'Translate By Tmtony
Sub Resize_Charts() Dim i AsInteger For i = 1To ActiveSheet.ChartObjects.Count With ActiveSheet.ChartObjects(i) .Width = 300 .Height = 200 EndWith Next i EndSub
Sub InsertMultipleSheets() Dim i AsInteger i = _ InputBox("Enter number of sheets to insert.", _ "Enter Multiple Sheets") Sheets.Add After:=ActiveSheet, Count:=i EndSub
Sub deleteBlankWorksheets() Dim Ws As Worksheet OnErrorResumeNext Application.ScreenUpdating= False Application.DisplayAlerts= False ForEach Ws In Application.Worksheets If Application.WorksheetFunction.CountA(Ws.UsedRange) = 0Then Ws.Delete EndIf Next Application.ScreenUpdating= True Application.DisplayAlerts= True EndSub
运行此代码,它将检查活动工作簿中的所有工作表,如果工作表为空,则将其删除。
45. 取消隐藏所有行和列
1 2 3 4
Sub UnhideRowsColumns() Columns.EntireColumn.Hidden = False Rows.EntireRow.Hidden = False End Sub
无需手动将行和列隐藏一个,您可以使用此代码一次性执行此操作。
46. 将每个工作表另存为单个 PDF
1 2 3 4 5 6 7 8 9
Sub SaveWorkshetAsPDF() Dimws As Worksheet ForEach ws In Worksheets ws.ExportAsFixedFormat _ xlTypePDF, _ "ENTER-FOLDER-NAME-HERE" & _ ws.Name & ".pdf" Next ws EndSub
此代码将简单地将所有工作表保存在单独的PDF文件中。您只需要从代码中更改文件夹名称即可。
47. 禁用分页符
1 2 3 4 5 6 7 8 9 10 11
Sub DisablePageBreaks() Dim wb As Workbook Dim wks As Worksheet Application.ScreenUpdating = False ForEach wb In Application.Workbooks ForEach Sht In wb.Worksheets Sht.DisplayPageBreaks = False Next Sht Next wb Application.ScreenUpdating = True EndSub'Translate By Tmtony
Sub VisibleWorkbooks() Dim book As Workbook Dim i AsInteger ForEach book In Workbooks If book.Saved = FalseThen i = i + 1 EndIf Next book MsgBox i EndSub
Sub HideSubtotals() Dim pt As PivotTable Dim pf As PivotField OnErrorResumeNext Set pt = ActiveSheet.PivotTables(ActiveCell.PivotTable.Name) If pt IsNothingThen MsgBox "You must place your cursor inside of a PivotTable." ExitSub EndIf ForEach pf In pt.PivotFields pf.Subtotals(1) = True pf.Subtotals(1) = False Next pf EndSub
如果要隐藏所有小计,只需运行此代码。首先,请确保从数据透视表中选择一个单元格,然后运行此宏。
57. 刷新所有数据透视表
1 2 3 4 5 6
Sub vba_referesh_all_pivots() Dim pt As PivotTable ForEach pt In ActiveWorkbook.PivotTables pt.RefreshTable Next pt EndSub'Translate By Tmtony
刷新所有数据透视表的超快速方法。只需运行此代码,工作簿中的所有数据透视表都将在一次射击中刷新。
58. 创建数据透视表
Follow this step by step guide to create a pivot table using VBA.
Sub UpdatePivotTableRange() Dim Data_Sheet As Worksheet Dim Pivot_Sheet As Worksheet Dim StartPoint As Range Dim DataRange As Range Dim PivotName AsString Dim NewRange AsString Dim LastCol AsLong Dim lastRow AsLong ' Set Pivot Table & Source Worksheet Set Data_Sheet = ThisWorkbook.Worksheets("PivotTableData3") Set Pivot_Sheet = ThisWorkbook.Worksheets("Pivot3") ' Enter in Pivot Table Name PivotName = "PivotTable2" ' Defining Staring Point & Dynamic Range Data_Sheet.Activate Set StartPoint = Data_Sheet.Range("A1") LastCol = StartPoint.End(xlToRight).Column DownCell = StartPoint.End(xlDown).Row Set DataRange = Data_Sheet.Range(StartPoint, Cells(DownCell, LastCol)) NewRange = Data_Sheet.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1) ' Change Pivot Table Data Source Range Address Pivot_Sheet.PivotTables(PivotName). _ ChangePivotCache ActiveWorkbook. _ PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange) ' Ensure Pivot Table is Refreshed Pivot_Sheet.PivotTables(PivotName).RefreshTable ' Complete Message Pivot_Sheet.Activate MsgBox "Your Pivot Table is now updated." EndSub
Sub AddChartTitle() Dim i As Variant i = InputBox("Please enter your chart title", "Chart Title") OnErrorGoTo Last ActiveChart.SetElement (msoElementChartTitleAboveChart) ActiveChart.ChartTitle.Text = i Last: ExitSub EndSub
Sub HideSubtotals() Dim pt As PivotTable Dim pf As PivotField OnErrorResumeNext Set pt = ActiveSheet.PivotTables(ActiveCell.PivotTable.name) If pt IsNothingThen MsgBox "You must place your cursor inside of a PivotTable." ExitSub EndIf ForEach pf In pt.PivotFields pf.Subtotals(1) = True pf.Subtotals(1) = False Next pf EndSub
Sub TableofContent() Dim i AsLong OnErrorResumeNext Application.DisplayAlerts = False Worksheets("Table of Content").Delete Application.DisplayAlerts = True OnErrorGoTo0 ThisWorkbook.Sheets.Add Before:=ThisWorkbook.Worksheets(1) ActiveSheet.Name = "Table of Content" For i = 1To Sheets.Count With ActiveSheet .Hyperlinks.Add _ Anchor:=ActiveSheet.Cells(i, 1), _ Address:="", _ SubAddress:="'" & Sheets(i).Name & "'!A1", _ ScreenTip:=Sheets(i).Name, _ TextToDisplay:=Sheets(i).Name EndWith Next i EndSub
Sub GoalSeekVBA() Dim Target AsLong OnErrorGoTo Errorhandler Target = InputBox("Enter the required value", "Enter Value") Worksheets("Goal_Seek").Activate With ActiveSheet.Range("C7") .GoalSeek_ Goal:=Target, _ ChangingCell:=Range("C2") EndWith ExitSub Errorhandler: MsgBox ("Sorry, value is not valid.") EndSub
目标寻求可以非常有助于您解决复杂的问题。在使用此代码之前,请在此处了解有关目标查找的详细信息。
71.在谷歌上搜索的VBA代码
1 2 3 4 5 6 7 8 9 10 11 12 13
Sub SearchWindow32() Dim chromePath AsString Dim search_string AsString Dim query AsString query = InputBox("Enter here your search here", "Google Search") search_string = query search_string = Replace(search_string, " ", "+") ' Uncomment the following line for Windows 64 versions and comment out Windows 32 versions' ' chromePath = "C:Program FilesGoogleChromeApplicationchrome.exe" ' Uncomment the following line for Windows 32 versions and comment out Windows 64 versions ' chromePath = "C:Program Files (x86)GoogleChromeApplicationchrome.exe" Shell (chromePath & " -url http://google.com/#q=" & search_string) EndSub
Sub convertToValues() Dim MyRange As Range Dim MyCell As Range SelectCase _ MsgBox("You Can't Undo This Action. " _ & "Save Workbook First?", vbYesNoCancel, _ "Alert") CaseIs = vbYes ThisWorkbook.Save CaseIs = vbCancel ExitSub EndSelect Set MyRange = Selection ForEach MyCell In MyRange If MyCell.HasFormula Then MyCell.Formula = MyCell.Value EndIf Next MyCell EndSub'Translate By Tmtony
只需将公式转换为值即可。运行此宏时,它会快速将公式更改为绝对值。
73.从所选单元格中删除空格
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Sub RemoveSpaces() Dim myRange As Range Dim myCell As Range SelectCaseMsgBox("You Can't Undo This Action. " _ & "Save Workbook First?", _ vbYesNoCancel, "Alert") CaseIs = vbYesThisWorkbook.Save CaseIs = vbCancel ExitSub EndSelect Set myRange = Selection ForEach myCell In myRange IfNotIsEmpty(myCell) Then myCell = Trim(myCell) EndIf Next myCell EndSub
Simply remove characters from the starting of a text string. All you need is to refer to a cell or insert a text into the function and number of characters to remove from the text string. It has two arguments “rng” for the text string and “cnt” for the count of characters to remove. For Example: If you want to remove first characters from a cell, you need to enter 1 in cnt.
Sub TimeStamp() Dim i AsInteger For i = 1To24 ActiveCell.FormulaR1C1 = i & ":00" ActiveCell.NumberFormat = "[$-409]h:mm AM/PM;@" ActiveCell.Offset(RowOffset:=1, ColumnOffset:=0).Select Next i EndSub
Sub removeChar() Dim Rng As Range Dim rc AsString rc = InputBox("Character(s) to Replace", "Enter Value") ForEach Rng In Selection Selection.Replace What:=rc, Replacement:="" Next EndSub
若要从所选单元格中删除特定字符,可以使用此代码。它将显示一个输入框,用于输入要删除的字符。
89. 整个工作表的字数统计
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Sub Word_Count_Worksheet() Dim WordCnt AsLong Dim rng As Range Dim S AsString Dim N AsLong ForEach rng In ActiveSheet.UsedRange.Cells S = Application.WorksheetFunction.Trim(rng.Text) N = 0 If S <> vbNullString Then N = Len(S) - Len(Replace(S, " ", "")) + 1 EndIf WordCnt = WordCnt + N Next rng MsgBox "There are total " _ & Format(WordCnt, "#,##0") & _ " words in the active worksheet" EndSub
Sub removeDecimals() Dim lnumber AsDouble Dim lResult AsLong Dim rng As Range ForEach rng In Selection rng.Value = Int(rng) rng.NumberFormat = "0" Next rng EndSub
此代码将仅帮助您从所选范围的数字中删除所有小数。
92. 将所有值乘以一个数字
1 2 3 4 5 6 7 8 9 10 11
Sub addNumber() Dim rng As Range Dim i AsInteger i = InputBox("Enter number to multiple", "Input Required") ForEach rng In Selection If WorksheetFunction.IsNumber(rng) Then rng.Value = rng + i Else EndIf Next rng EndSub'Translate By Tmtony
Sub addNumber() Dim rng As Range Dim i AsInteger i = InputBox("Enter number to multiple", "Input Required") ForEach rng In Selection If WorksheetFunction.IsNumber(rng) Then rng.Value = rng + i Else EndIf Next rng EndSub
就像乘法一样,您也可以将一个数字加到一组数字中。
94. 计算平方根
1 2 3 4 5 6 7 8 9 10
Sub getSquareRoot() Dim rng As Range Dim i AsInteger ForEach rng In Selection If WorksheetFunction.IsNumber(rng) Then rng.Value = Sqr(rng) Else EndIf Next rng EndSub