Seample MACROS that are cammonly used:Auto RunMaking your macros run automatically when opening your workbook. You can either use the Auto Open method or the Workbook Open method.Active CellAn active cell is the current cell that is selected. This term is used in many macros. This can be used as a marker. A good example is when you need to move from your current cell. Refer to Moving your cursor macro.
Adding Items to a combobox
To add a combobox refer to User Form. To populate a combobox or a listbox is the same. You could add from the code or even from a range of cells in your spreadsheet. To add from the code, just add this line to your code. ComboBox1.AddItem "Product A"
ComboBox1.AddItem "Product B" Counting Rows & Columns & SheetsWhen you have selected a range, it is sometimes useful to know how many rows or columns you have selected as this information can be used in your macros (for eg when you have reached the end, you will know it is time to stop the macros. This macro will do the trick.
Sub Count()myCount = Selection.Rows.Count 'Change Rows to Columns to count columnsMsgBox myCountEnd SubThe next macro counts the number of sheets instead. Refer to Protecting all sheets macro which uses this method.
Sub Count2()myCount = Application.Sheets.CountMsgBox myCountEnd SubCarriage ReturnSometimes you may want to put a line of text on the next row and not let it continue on the first row. See this example in a message box.
Sub TwoLines() MsgBox "Line 1" & vbCrLf & "Line 2" End SubClose All FilesSometimes you may want to close all files without saving. Doing it manually is a hassle with the question "Do you wanna save?"
Sub CloseAll()Application.DisplayAlerts = FalsemyTotal = Workbooks.CountFor i = 1 To myTotal ActiveWorkbook.CloseNext iEnd SubCopying A RangeCopy data from a specific range can be done with this macro. Here data is copied from the current sheet to the activecell.
Sub CopyRange()Range("A1:A3").Copy Destination:=ActiveCellEnd SubTo copy from a range in another sheet (eg Sheet3) to the active cell you need to change the code to;
Sheets("sheet3").Range("A1:A3").Copy Destination:=ActiveCell
CounterTo use a counter in your macro, just assign any cell to retain the value. In this example the cell A1 is chosen. Each time the macro is run, it adds the value 1 to the cell A1.
Sub Count() mycount = Range("a1") + 1 Range("a1") = mycountEnd SubCurrent DatePrivate Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)Range("A1") = Now 'Select any cell you want End SubCurrent Cell ContentTo know what the cell contains ie dates, text or formulas before taking a course of action. In this example a message box is displayed. Replace this with a macro should you require another course of action.
Sub ContentChk()If Application.IsText(ActiveCell) = True ThenMsgBox "Text" 'replace this line with your macroElseIf ActiveCell = "" ThenMsgBox "Blank cell" 'replace this line with your macroElseEnd IfIf ActiveCell.HasFormula ThenMsgBox "formula" 'replace this line with your macroElseEnd IfIf IsDate(ActiveCell.Value) = True ThenMsgBox "date" 'replace this line with your macroElseEnd IfEnd IfEnd Sub Current Cell Position and ValueSometimes we need to know the current cell position. This would do the trick.
Sub CellActivePositionValue()myRow = ActiveCell.RowmyCol = ActiveCell.ColumnMyCellValue = ActiveCell.ValueMsgBox myRow & "," & myCol & "," & MyCellValueEnd SubDeleting Empty RowsTo delete empty rows in a selected range we can use the following macro. The macro here uses the For Next Loop. First the macro counts the rows in a selected range to determine the when the macro should stop. The For Next statement acts as a counter.
Sub DelEmptyRow()Rng = Selection.Rows.CountActiveCell.Offset(0, 0).SelectApplication.ScreenUpdating = FalseFor i = 1 To RngIf ActiveCell.Value = "" Then 'You can replace "" with 0 to delete rows with 'the value zeroSelection.EntireRow.DeleteElseActiveCell.Offset(1, 0).SelectEnd IfNext iApplication.ScreenUpdating = TrueEnd SubThe statement "Application.ScreenUpdating = False" prevents the screen from updating to ensure the macro runs faster and the screen will not flicker. Don't forget to set it back to "True".
Deleting Range NamesTo delete all the range names in your workbook, this macro will do the trick.
Sub DeleteNames()Dim NameX As NameFor Each NameX In NamesActiveWorkbook.Names(NameX.Name).DeleteNext NameXEnd SubFind Mutches in two collumsSub Find_MatchesInTwoCol()Dim CompareRange As Variant, x As Variant, y As Variant' Usage: Leav Colum B empty ' Set CompareRange equal to the range to which you will compare the selection. Set CompareRange = Range("C1:C5") '<== set range here' NOTE: If the compare range is located on another workbook or worksheet, use the following syntax.' Set CompareRange = Workbooks("Book2").Worksheets("Sheet2").Range("C1:C5")' Loop through each cell in the selection and compare it to each cell in CompareRange.For Each x In Selection For Each y In CompareRange If x = y Then x.Offset(0, 1) = x Next y Next xEnd SubDuplicatesIf you need to delete duplicate data in your worksheet that are in same column. This macro does the trick.
Public Sub DeleteDuplicateRows()' This macro will delete all duplicate rows which reside under' the first occurrence of the row.' Use the macro by selecting a column to check for duplicates' and then run the macro and all duplicates will be deleted, leaving' the first occurrence only.
Dim R As LongDim N As LongDim V As VariantDim Rng As RangeOn Error GoTo EndMacroApplication.ScreenUpdating = FalseApplication.Calculation = xlCalculationManualSet Rng = Application.Intersect(ActiveSheet.UsedRange, _ ActiveSheet.Columns(ActiveCell.Column))Application.StatusBar = "Processing Row: " & Format(Rng.Row, "#,##0")N = 0For R = Rng.Rows.Count To 2 Step -1If R Mod 500 = 0 Then Application.StatusBar = "Processing Row: " & Format(R, "#,##0")End IfV = Rng.Cells(R, 1).ValueIf V = vbNullString Then If Application.WorksheetFunction.CountIf(Rng.Columns(1), vbNullString) > 1 Then Rng.Rows(R).EntireRow.Delete N = N + 1 End IfElse If Application.WorksheetFunction.CountIf(Rng.Columns(1), V) > 1 Then Rng.Rows(R).EntireRow.Delete N = N + 1 End IfEnd IfNext REndMacro:Application.StatusBar = FalseApplication.ScreenUpdating = TrueApplication.Calculation = xlCalculationAutomaticMsgBox "Duplicate Rows Deleted: " & CStr(N)End SubHow to Highligh duplicateSelect the cells that you want to highlight. Under the Home tab, under Styles, Click Conditional Formatting. Go to Highlight Cell Rules and Click Duplicate Values. ![]() How to remove duplicates in same colon in Excel? Select the row or column that has duplicates that you would like to remove. Go to Data -> Filter -> Advanced Filter, and type : $A$1:$A$17 Make sure the range is correct and check the option “unique records only“. To email your current workbook the following code.Sub Email()ActiveWorkbook.SendMail recipients:="neven@NTCenter.com"End SubTo Launch Program whitin ExcelType in CELL: = HYPERLINK("file:///c:\WINDOWS\system32\CALC.exe","CALC")
Note, if you need to run a program with switches or argumentes, then you need to creat the CMD batch file since it can't be passed directly in the hyperlink. OR
Run external program with VBA Shell finctionSub SUMO1() Q = MsgBox("RUN SUMO Check?", vbYesNo, "Running SUMO, please wait...")If Q = vbNo ThenMsgBox "Exiting..."ElseFileToLaunch = "C:\Exxon\QA\SUMO\sumocheck-2.vbs"CMD_ARG = "TORSCC02 /htmllog:TORSCC01_SUMO_Report.html /IE"programPath = "cscript.exe"Shell programPath + " " + FileToLaunch + " " + CMD_ARG, vbNormalFocusEnd IfEnd Sub |
