Sunday, May 06, 2012
Excel VBA uninstall Excel Addins
Friday, August 21, 2009
How to add Format Conditions using Excel VBA
Conditional Formatting using Excel VBA
Here is a small snippet for FormatConditions.
Sub Format_Condition_Example()
Dim oFc As FormatCondition
Dim oRange As Range
Set oRange = Range("B2:B5")
Set oFc = oRange.FormatConditions.Add(xlCellValue, xlLess, "0.5")
oFc.Interior.ColorIndex = 3
Set oFc = oRange.FormatConditions.Add(xlCellValue, xlBetween, "0.5", "0.80")
oFc.Interior.ColorIndex = 6
Set oFc = oRange.FormatConditions.Add(xlCellValue, xlGreater, "0.80")
oFc.Interior.ColorIndex = 4
End Sub
See also:
How to Search a specific Colored Text (Range) using Excel VBA
Format ListColumns using VBA
How to Hide the PivotTable Fields List using VBA
Excel VBA - Hide Pivot Table Fields List
If you are developing some pivot table as part of the report and feel the Pivot Fields list at the right corner is bit distracting, you can turn it off as shown below:
Sub Hide_PivotTable_Fields()
ActiveWorkbook.ShowPivotTableFieldList = False 'Dont Show the Pivot Table List
End Sub
Tuesday, July 14, 2009
How to Create New Menu using Excel VBA
Here is a code to add a new menu and a button whenever a sheet is opened.
Option Explicit
Private Const APPNAME As String = "Sample Menu"
Private Sub Workbook_Open()
Dim ctlNewMenu As CommandBarControl
Dim ctlNewGroup As CommandBarControl
Dim ctlNewItem As CommandBarControl
Dim vID
On Error GoTo Err_DUD
On Error Resume Next
Application.CommandBars("Worksheet Menu Bar").Controls(APPNAME).Delete
On Error GoTo 0
Set ctlNewMenu = Application.CommandBars("Worksheet Menu Bar").Controls.Add(Type:=msoControlPopup)
ctlNewMenu.Caption = APPNAME
'--- Add Control Buttons ---------------
Set ctlNewItem = ctlNewMenu.Controls.Add(Type:=msoControlButton)
ctlNewItem.Caption = "Sample Button"
ctlNewItem.OnAction = "SayHello"
ctlNewItem.TooltipText = "Sample Button by VBADUD"
Err_DUD:
If Err <> 0 Then
Err.Clear
Resume Next
End If
End Sub
Sunday, February 22, 2009
How to use non-contiguous range of cells in Excel VBA
Here is a way to update a range that is not contiguous using VBA
Sub NonContiguous_Range_Example()
Dim oRng As Range
Set oRng = Range("A1, B5, C9")
oRng.Value = "45"
oRng.Interior.ColorIndex = 34
End Sub
The output will be as shown below:
Saturday, October 11, 2008
Excel VBA uninstall Excel Addins
Programmatically uninstall Excel Addins using VBA
Sub UnInstall_Addins_From_EXcel_AddinsList()
Dim oXLAddin As AddIn
For Each oXLAddin In Application.AddIns
Debug.Print oXLAddin.FullName
If oXLAddin.Installed = True Then
oXLAddin.Installed = False
End If
Next oXLAddin
End Sub
See also:
Call a Method in VSTO Addin from Visual Basic Applications
Programmatically Delete Word Addins from the Addins List using VBA
UnInstall Word Addins using VBA
Tuesday, September 30, 2008
Add Macro to Workbook programatically using Excel VBA
Here is a simple procedure to add a macro to the current workbook using VBComponents
Sub Add_Macro_To_ThisWorkbook()
Dim VBP As VBProject
Dim VBM As VBComponent
Dim VBModule As CodeModule
Dim VBProc As VBComponent
Set VBP = ThisWorkbook.VBProject
Set VBModule = VBP.VBComponents.Item("ThisWorkbook").CodeModule
VBModule.AddFromString ("Sub Sample_Macro" & vbCrLf & "ret = msgbox (""Hello VBADUD"") " & vbCrLf & "End Sub")
End Sub
Sunday, March 02, 2008
Delete Comments from Excel Workbook using VBA
Most of the times comments are used for internal purpose. This need not go with the workbbok, here is the way to remove it
Sub Remove_Comments_From_WKBK()
'
' Remove Comments from Excel 2007 Workbook
'
'
ActiveWorkbook.RemoveDocumentInformation (xlRDIComments)
End Sub
If you want the same for Excel 2003 and before here is the code
Sub Remove_Comments_From_WKBK_2003()
'
' Remove Comments from Excel 2003 Workbook
'
'
Dim wks As Worksheet
Dim cmnt As Comment
For Each wks In ActiveWorkbook.Sheets
For Each cmnt In wks.Comments
cmnt.Delete
Next cmnt
Next
End Sub
Saturday, October 06, 2007
Excel VBA - FindAll Method
Function FindAll(ByVal sText As String, ByRef oSht As Worksheet, ByRef sRange As String, ByRef arMatches() As String) As Boolean
' --------------------------------------------------------------------------------------------------------------
' FindAll - To find all instances of the1 given string and return the row numbers.
' If there are not any matches the function will return false
' --------------------------------------------------------------------------------------------------------------
On Error GoTo Err_Trap
Dim rFnd As Range ' Range Object
Dim iArr As Integer ' Counter for Array
Dim rFirstAddress ' Address of the First Find
' -----------------
' Clear the Array
' -----------------
Erase arMatches
Set rFnd = oSht.Range(sRange).Find(What:=sText, LookIn:=xlValues, LookAt:=xlPart)
If Not rFnd Is Nothing Then
rFirstAddress = rFnd.Address
Do Until rFnd Is Nothing
iArr = iArr + 1
ReDim Preserve arMatches(iArr)
arMatches(iArr) = rFnd.Address ' rFnd.Row ' Store the Row where the text is found
Set rFnd = oSht.Range(sRange).FindNext(rFnd)
If rFnd.Address = rFirstAddress Then Exit Do ' Do not allow wrapped search
Loop
FindAll = True
Else
' ----------------------
' No Value is Found
' ----------------------
FindAll = False
End If
' -----------------------
' Error Handling
' -----------------------
Err_Trap:
If Err <> 0 Then
MsgBox Err.Number & " " & Err.Description, vbInformation, "Find All"
Err.Clear
FindAll = False
Exit Function
End If
End Function
The functions accepts three input parameters - Text To be searched, Worksheet, Search Range and one output Array parameter
The function searches the occurrence of that particular text in the specified range of the Excel Sheet and returns address(es) of all occurrences. The Search is by default part of Excel Cells and not whole cell
Here is a way to implement the function:
Case I : Get Addresses of all matching cells
Sub Drive_The_FindAll_Function()
' Sample Sub to Drive the Function
Dim arTemp() As String 'Temp Array
Dim bFound As Boolean 'Flag
Dim i1 As Integer 'Array Counter
bFound = FindAll("SampleText", ActiveSheet, "B1:C41", arTemp())
If bFound = True Then
For i1 = 1 To UBound(arTemp)
' The Address Can be used for extracting data
MsgBox arTemp(i1)
Next i1
Else
MsgBox "Search Text Not Found"
End If
End Sub
Case II : Modify Data according to Find
In the example shown below, FindAll function is used to search 'SampleText' in column C and if the text is found a Flag 'X' is set against column D
Sub Fill_Based_on_FindAll()
' For All Matching Values in Second Column
' Add 'X' to Column D
Dim arTemp() As String 'Temp Array
Dim bFound As Boolean 'Flag
Dim i1 As Integer 'Array Counter
bFound = FindAll("SampleText", ActiveSheet, "C:C", arTemp())
If bFound = True Then
For i1 = 1 To UBound(arTemp)
' The Row Number Can be used for extracting data
ActiveSheet.Range(arTemp(i1)).Offset(0, 1).Value = "X"
Next i1
Else
MsgBox "Search Text Not Found"
End If
End Sub
Case III : Get the Number of Occurrences
A simple one though; number of occurrences of the text in particular range
Sub Instances_Based_on_FindAll()
' Get the Number of Instances
Dim arTemp() As String 'Temp Array
Dim bFound As Boolean 'Flag
Dim i1 As Integer 'Array Counter
bFound = FindAll("SampleText", ActiveSheet, "C:C", arTemp())
If bFound = True Then
MsgBox "No of instances : " & UBound(arTemp)
Else
MsgBox "Search Text Not Found"
End If
End Sub
Disabling Macros in a Workbook (Excel VBA)
The following code snippet (Excel 2003) uses Application.FileDialog method to open a Workbook and disables the macros in it:
Sub Open_File_With_Macros_Disabled()
Dim i1 As Integer
Dim secAutomation As MsoAutomationSecurity
secAutomation = Application.AutomationSecurity
Application.AutomationSecurity = msoAutomationSecurityForceDisable
With Application.FileDialog(msoFileDialogOpen)
.Show
For i1 = 1 To .SelectedItems.Count
MsgBox .SelectedItems(i1)
Workbooks.Open .SelectedItems(i1)
Next i1
End With
Application.AutomationSecurity = secAutomation
End Sub
Saturday, September 15, 2007
Excel VBA - Change Font Color for Part of Text
Sometimes, you need to differentiate some parts of text in an Excel cell. This can be done using formatting those characters.
Here is the way that can be done using VBA using the Characters property
Sub Color_Part_of_Cell()
'Print ActiveCell.Characters.Count
With ActiveCell.Characters(2).Font
.Color = RGB(36, 182, 36)
End With
With ActiveCell.Characters(2, 2).Font
.Color = RGB(36, 182, 36)
End With
With ActiveCell.Characters(, 2).Font
.Color = RGB(36, 182, 36)
End With
End Sub
The output of the above is

Syntax
expression.Characters(Start, Length)
expression Required. An expression that returns an object in the Applies To list.
Start Optional Variant. The first character to be returned. If this argument is either 1 or omitted, this property returns a range of characters starting with the first character.
Length Optional Variant. The number of characters to be returned. If this argument is omitted, this property returns the remainder of the string (everything after the Start character)
The same characters object can be used to make a character Bold / Italic
Orientation of Cell Through Excel VBA
Here is an example
Sub Orientations()
ActiveCell.Orientation = xlHorizontal
ActiveCell.Orientation = xlVertical
ActiveCell.Orientation = xlUpward
ActiveCell.Orientation = xlDownward
ActiveCell.Orientation = 45
ActiveCell.Orientation = -45
End Sub
The orientation of the cell in Excel would be as follows:

Wednesday, July 25, 2007
Excel Height of Row - RowHeight using Excel VBA
Returns the height of all the rows in the range specified, measured in points (point: Unit of measure referring to the height of a printed character. A point equals 1/72 of an inch, or approximately 1/28 of a centimeter.). Returns null if the rows in the specified range aren’t all the same height. Read/write Variant.
You can use the Height property to return the total height of a range of cells.
Sub Change_Header_Row_Height()
MsgBox "RowHeight = " & Range("A1").RowHeight _
& vbCrLf & "Height = " & Range("A1").Height
Range("A1").RowHeight = 90
End Sub
Differences between RowHeight and Height include the following:
Height is read-only.
If you return the RowHeight property of several rows, you will either get the row height of each of the rows (if all the rows are the same height) or null (if they’re different heights). If you return the Height property of several rows, you will get the total height of all the rows.
Range("A1").Height = 90
would give Object required 424 error
Technorati Profile
Wednesday, June 13, 2007
Excel VBA - Delete Empty Rows
Here is a primitive simple function to delete rows that does not contain any value (I have taken Cols 1 to 10) for consideration.
Sub Delete_UnWanted_Rows()
For Each SHT In Sheets
SHT.Activate
iMax = SHT.Cells.SpecialCells(xlCellTypeLastCell).Row
For i2 = 2 To iMax
For i1 = 1 To 10
If LenB(SHT.Cells(i2, i1)) <> 0 Then
GoTo TakeNextRow
End If
Next i1
SHT.Rows(i2).EntireRow.Delete
TakeNextRow:
Application.StatusBar = SHT.Name & " " & i2
Next i2
TakeNextSht:
Next SHT
Application.StatusBar = False
End Sub
You can do the same with Special Cells - LastCell also
Sunday, May 27, 2007
Save copy of the workbook
'Saves a copy of the workbook to a file but doesn't modify the open workbook in memory
Dim bAchievedTarget As Boolean
If bAchievedTarget = True Then
ActiveWorkbook.SaveCopyAs "c:\Completed\FinalCopy.xls"
End If
' This function can be used to take the copy of the file while working on it. The current file remains the same however
End Sub
See also :
Excel VBA - 1004 -- The file could not be accessed
Save and Reopen all Workbooks (Excel VBA)
Save copy of the workbook
SaveAs Dialog - Controlled Save
Save RTF document as word
Print Multiple Sheets using VBA
Sub Print_Selected_Sheets()
' Remove Multiple Selections
ActiveWorkbook.Sheets(1).Select
' Select Multiple Sheets - Optional False is to extend the current selection to include any previously selected objects and the specified object
ActiveWorkbook.Sheets(1).Select False
ActiveWorkbook.Sheets(2).Select False
ActiveWorkbook.Sheets(4).Select False
' -----------------------------------------------------------
' Coded by Shasur for http://vbadud.blogspot.com
' -----------------------------------------------------------
ActiveWindow.SelectedSheets.PrintOut Copies:=1
' Remove Multiple Selections
ActiveWorkbook.Sheets(1).Select
End Sub
Saturday, May 26, 2007
Insert Procedure to a Module Using VBComponents
Sub Insert_PRocedure_To_BasModule()
' This program will need reference to Microsoft Visual Basic for Extensibility Library
Dim VBP As VBProject
Dim VBC As VBComponent
Dim VBMod As CodeModule
' -----------------------------------------------------------
' Coded by Shasur for http://vbadud.blogspot.com
' -----------------------------------------------------------
Workbooks.Add
Set VBP = ActiveWorkbook.VBProject
Set VBC = VBP.VBComponents.Add(vbext_ct_StdModule)
VBC.Name = "MyMacro"
Set VBMod = VBC.CodeModule
VBMod.InsertLines 3, "Sub NewProc()" & Chr(13) & _
" Msgbox ""Welcome to VB Component Programming"" " & Chr(13) & _
"End Sub"
End Sub
Dynamic Insertion of Procedure Bas Module, Dynamic Creation of Function / Procedure in BAS/Class Module, Automatic Creation of Function / Procedure in BAS/Class Module, Create New Module using VBA, VBA Create Module, VBA Attach Module to Workbook
Delete Module on the Fly using VBA
Sub Delete_BasModule_To_WorkBook()
' This program will need reference to Microsoft Visual Basic for Extensibility Library
Dim VBP As VBProject
Dim VBC As VBComponent
Dim VBMod As CodeModule
' -----------------------------------------------------------
' Coded by Shasur for http://vbadud.blogspot.com
' -----------------------------------------------------------
Set VBP = ActiveWorkbook.VBProject
Set VBC = VBP.VBComponents("MyMacro")
' Delete the module
ActiveWorkbook.VBProject.VBComponents.Remove VBC
End Sub
Dynamic Deletion of Bas Module, Dynamic Deletion of Bas Module, Automatic Deletion of Bas Module, Delete Module using VBA, VBA Delete Module, VBA Detach Module to Workbook
Insert User Form on the Fly
Sub Insert_Form_To_WorkBook()
' This program will need reference to Microsoft Visual Basic for Extensibility Library
Dim VBP As VBProject
Dim VBC As VBComponent
Dim VBMod As CodeModule
' -----------------------------------------------------------
' Coded by Shasur for http://vbadud.blogspot.com
' -----------------------------------------------------------
Workbooks.Add
Set VBP = ActiveWorkbook.VBProject
Set VBC = VBP.VBComponents.Add(vbext_ct_MSForm)
VBC.Name = "frmMyForm"
End Sub
Dynamic Insertion of User Form, Dynamic Creation of User Form, Automatic Creation of User Form, Dynamically Create New User Form using VBA, VBA Create Module, VBA Attach Module to Workbook
Insert Class Module on the Fly
Sub Insert_Class_Module_To_WorkBook()
' This program will need reference to Microsoft Visual Basic for Extensibility Library
Dim VBP As VBProject
Dim VBC As VBComponent
Dim VBMod As CodeModule
' -----------------------------------------------------------
' Coded by Shasur for http://vbadud.blogspot.com
' -----------------------------------------------------------
Workbooks.Add
Set VBP = ActiveWorkbook.VBProject
Set VBC = VBP.VBComponents.Add(vbext_ct_ClassModule)
VBC.Name = "clsMyClass"
End Sub
Dynamic Insertion of Class Module, Dynamic Creation of Class Module, Automatic Creation of Class Module, Create New Module using VBA, VBA Create Module, VBA Attach Module to Workbook