Excel VBA by Index (1
Excel VBA by Index (1
Excel VBA by Index (1
Share
Table of Contents | ext I have compile a list of Excel VBA code for beginner in an indexing format. More code will be added from time to time.
L Y
M Z
Your Ad Here
ActiveSheet If you want to refer to the currently selected worksheet in a workbook, you can do so by using the ActiveSheet property. For example, the subroutine below will enter the value 100 into cell A1 in Worksheets(2) as the current selected worksheet. Sub ActiveSheetDemo ( ) ActiveSheet.Cells(1,1).Value = 100
End Sub.
Add comments to a Cell (back to top) In order to add comment to a cell, you can use the AddComment method with the Range object. The macro below will show you how. Sub AddCommentDemo ( ) Range("A1").AddComment "Prevent Global Warming" End Sub Here the word "Prevent Global Warming" is added as a comment for cell A1. To display this comment all the time insert the following code..
http://www.xlpert.com/vba_index.htm 1/17
Add Method (back to top) Add a workbook and input a value in Range A1 of workbook created. Sub AddWorkbook () Workbooks.Add intWorkbooksCount = Workbooks.Count Set ReportWorkbook = Workbooks(intWorkbooksCount) Set sht1 = ReportWorkbook.Worksheets(1) sht1.Cells(1, 1) = "Welcome" End Sub
The code below show how to populate a combobox or a listbox . ComboBox1.AddItem "Boston" ComboBox1.AddItem " ew York"
Address To specify a range reference in a style we are familiar with, like A1 or E5. The Excel VBA procedure below will find a cell that has formula content and will display the address of this cell in a message box. Sub AddressDemo () Set MyRange = Range("A1:Z1000") For Each cell in MyRange If cell.HasFormula = True Then MsgBox cell.Address Exit For ext cell End Sub
And Operator (back to top) Perform a logical conjunction on two expression. In this case, two expression has to be satisfied in order for the macro to continuerunning. The macro below show how: Sub AndDemo () x=1 y =2
http://www.xlpert.com/vba_index.htm 2/17
Areas Collection (back to top) The Areas collection contains a few block of cells within a specific selection i.e. multiple ranges to create one multi-range. Let's look at an example... Sub AreasDemo() Dim rng1 As Range, rng2 As Range, rng3 As Range, myRange As Range Dim AreasInMyRange As Integer Set rng1 = Range("A1:B10") Set rng2 = Range("D1:D10") Set rng3 = Range("G1:G10") Set myRange = Union(rng1, rng2, rng3) AreasInMyRange = myRange.Areas.Count End Sub The above macro use the Union function to combine 3 non-contiguous ranges. AreasInMyRange will return 3 as we use the Areas.Count method to calculate the 3 areas in myRange. Autofill Method This method enable user to autofill a series of data on the specified range of cells. Look at the example below. Sub AutofillDemo ( ) Range("A1:B1").Autofill Range("A1:J1") End Sub The above will autofills cells C1 through J1 using the source data in cells A1 and B1. If A1 contains 1 and B1 contains 2, then this code will fill the destination cells with consecutive integers starting at 3 (in cell C1), 4 (in cell D1) and so on
B
Built -in Functions (back to top) This code will use the Excel built-in function, Average, Max, Min and Standard Deviation. Option Base 1 Sub BuiltInFunctionDemo () Dim MyArray(100) As Integer For x = 1 to 100 MyArray(x) = Rnd
http://www.xlpert.com/vba_index.htm 3/17
4/13/2011 ext x
average = Application.Average(MyArray) max = Application.Max(MyArray) min = Application.Min(MyArray) std = Application.Stdev(MyArray) End Sub
Calculate a specific cell Excel will calculate that worksheet. When applied to a specific range, as in: Worksheets(1).Rows(2).Calculate With the above syntax, Excel VBA will calculate only row 2 in worksheet 1. If you want to calculate all the formula in worksheet 1 then insert the following code... Worksheets(1).Calculate
Your Ad Here
Calling a Worksheet Function from Visual Basic (back to top) In Visual Basic, the Microsoft Excel worksheet functions are available through the WorksheetFunction object. The following procedure uses the Max worksheet function to determine the largest value in a range of cells Sub FunctionDemo() Set myRange = Worksheets("Sheet1").Range("A1:B10") ans = Application.WorksheetFunction.Max(myRange) MsgBox ans End Sub The range A1:B10 on Sheet1 is Set as myRange. Another variable, ans, is assigned the result of applying the Max function to myRange which then show up in a message box when you execute the procedure.
Cells Method (back to top) To enter the the value 100 into Range("B2"), the code below will do the trick... ActiveSheet.Cells(2,2).Value = 100 We can also reference a specific cell in a Range object by using the code below...Here the value 100 is enter into Range("C4") Set MyRange = Range("C3:C10") MyRange.Cells(2).Value = 100
http://www.xlpert.com/vba_index.htm
4/17
To change text in a selected range to proper case use the code below. Sub ProperCaseDemo() Dim cell As Range For Each cell In Selection.Cells If cell.HasFormula = False Then cell = strconv(cell.text,vbProperCase) End If ext End Sub
Change the name of a Worksheet You can change the name of a worksheet by using the Name property of the Worksheet object. The macro below will show you how. Sub Change ameDemo ( ) Dim ws ame As String ws ame = InputBox("Enter a new worksheet name") ActiveSheet. ame = ws ame End Sub
Clear method This method enables you to clear the entire values, formulas and formatting from a range of cells. The procedure below use different Clear method.. Sub ClearDemo ( ) Range("A101:E200").ClearContents Range("A201:E300").ClearFormats Range("A1:E100").Clear End Sub 'will clear the cell values and formulas from a range of cells except the formatting 'to clear the formatting 'will clear the entire values, formulas and formatting from a range of cells
Copying a range (back to top) This is how you write a simple copy and paste operation... Sub CopyDemo () ActiveSheet.Range("A1:A3"). Copy (ActiveSheet.Range("B1:B3")) End Sub
Columns properties With this property, you can select the entire column as the Range object. RangeSelected = Columns(3)
http://www.xlpert.com/vba_index.htm 5/17
4/13/2011
Here column C is selected. You can also use the Columns property to determine a specific Column within a Range. For example, look at the procedure below. Sub ColumnDemo ( ) Set MyRange = Range(B1:E100). MyRange.Columns(2).Select End Sub Here you have selected Range(C1:C100) as it is the second column within B1:E100. Comparing two strings (back to top) The Excel built-in function StrComp is use to compare whether two strings are alike. Let me show you how with the macro below. Sub CompareString ( ) aStr = ActiveSheet.Range("A1").Value bStr = ActiveSheet.Range("A2").Value If StrComp(aStr,bStr) = 0 Then MsgBox "They match" Else MsgBox "They are not the same" End If End Sub
Create Chart Sheet To create a chart sheet, we can use the Add method of the Charts collection to create and add a new chart sheet to the workbook. The macro below will do the trick. Sub CreateChartDemo ( ) Dim ch As Chart Set ch = ThisWorkbook.charts.Add() ch. ame = "Account" End Sub
Current Cell Content (back to top) If you want to know what the cell contains ie dates, text or formulas before a block of code is executed, you can use the code below. Replace this with the code you want to execute. Sub ContentDemo()
http://www.xlpert.com/vba_index.htm
6/17
4/13/2011 Excel VBA By Index (1) If Application.IsText(ActiveCell) = True Then MsgBox "Text" 'block of code to be executed
End If
End Sub
Customize background color of cell You can customize the background of cell and range of cells by using the ColorIndex property with the Interior object. Sub ColorIndexDemo ( ) Cells(1,1).Interior.ColorIndex = 3 Cells(1,2).Interior.ColorIndex = 5 'set to red 'set to blue
Custom Functions (back to top) I bet you're familiar with Excel built-in function like Sum, Average, Max, PMT etc. If you feel that's not enough then you can create custom functions by using Excel VBA. Let's create our own cubic function. Public Function Cubic (num) Cubic = num ^ 3 End Function
D
Delete (back to top) To delete a worksheet, use the following code..Worksheet(2) will be deleted Sub DeleteSheetDemo1 () Worksheets(2).Delete End Sub When you delete a sheet, Excel will display a message to warn user whether they want to
http://www.xlpert.com/vba_index.htm
Your Ad Here
7/17
4/13/2011 Excel VBA By Index (1) delete the sheet or not. To disable this message, use the code below
Disable the Ctrl + Break and Esc key (back to top) In order for you to prevent user to stop a macro before it finish running by pressing the Ctrl + Break and Esc key, just insert the code below at the top of your procedure... Application.EnableCancelKey = False
DisplayFullScreen The macro below show you how to display fullscreen using Excel VBA Application.DisplayFullScreen = True To exit full screen using VBA then Application.DisplayFullScreen = False
Do Until loop. When you use the Do Until loop, the code you enter between the Do and Loop will execute until the specified condition is met. Sub DoDemo ( ) Dim x As Integer x=1 Do Until IsEmpty(Cells(x,1)) Cells(x,1).Font.Bold = True x=x+1 Loop End Sub The macro will execute until the cell in Column A is empty.
Your Ad Here
E
http://www.xlpert.com/vba_index.htm 8/17
You can use the End of the Range object to select a particular. See this example... Sub EndDemo () Range(ActiveCell, ActiveCell.End(xlDown)).Select Range(ActiveCell, ActiveCell.End(xlUp)).Select Range(ActiveCell, ActiveCell.End(xlToLeft)).Select 'select downward the activecell to last non-empty cell 'select upward the activecell to last non-empty cell 'select to the left of the activecell to last non-empty cell
Range(ActiveCell, ActiveCell.End(xlToRight)).Select 'select to the right of the activecell to last non-empty cell End Sub
Err The default syntax of Excel VBA. This example demonstrates error handling by jumping to a label.. Sub ErrDemo () Dim x As Integer On Error GoTo ErrorHandler x = "abc" Exit Sub ErrorHandler: e = Err. umber & " ...cannot assign integer value to x" MsgBox (e) End Sub
Exit Do (back to top) If you need to jump out from a Do loop, you can do this by using the Exit Do statement. The macro below will do the trick. Sub ExitDoDemo ( ) x=1 y = 100 Do While x < y If x^2 > 100 Then Exit Do x=x+1 Loop End Sub The procedure will halt when x^2 is more than 100.
4/13/2011 Excel VBA By Index (1) The Exit Sub statement is use as a point of exiting a subroutine with running the rest of any other statement in a procedure. The example below will display a message box to prompt the user whether to continue or not. If user choose yes, the subroutine will call the macro MyProcdure and will exit the current subroutine.
Sub ExitSubDemo ( ) msg = "Do you want to continue?" answer = MsgBox(msg,vbYes o) If answer = vbYes Then Call MyProcedure Exit Sub Else MsgBox "Program will end now." End if End Sub
F
Fill Method You can use the Fill method to fills a range of cells. Let's see how this is implemented below. Sub FillDemo ( ) Range("A2:A10").FillUp Range("A2:A10").FillDown End Sub Find a File (back
to top)
'this will fill up the value contain in cell A10 to all cell above until A2 'this will fill down the value contain in cell A2 to all cell below until A10
In order to search for a file in your system, you can use the FileSearch object. The macro below will do the trick. Sub FileSearchDemo ( ) Dim PathInfo As String With Application.FileSearch . ewSearch .File ame = Computer.xls End With End Sub You must make that such file exist, else Excel VBA will return an error message. Font Object Properties of this object includes Bold, Size, Italic, Underline and etc. To set the font properties you can enter the code as follow Sub FontDemo ( ) Set SelFont = ActiveSheet.Range(A1).Font
http://www.xlpert.com/vba_index.htm 10/17
4/13/2011
SelFont.Font.Size = 12 SelFont.Font.Bold = True End Sub The above procedure enables you to set the font of cell A1 to size 12 and bold. For ext Loop (back to top) Use this syntax when you want to execute for a determine number of time. Sub For extDemo1 () For x = 1 to 10 y=x+1 ext x MsgBox (y) End Sub Here you'll get y = 11 Look at another example...The code below will for cell value that are positive to bold. Sub For extDemo2 () Set MyRange = Range("A1:A100") y = MyRange.Rows.Count ' y = 100 For x = 1 to y If MyRange.Cells(x).Value > 0 Then MyRange.Cells(x).Font.Bold = True End If ext x End Sub Or you can use the For Each - ext syntax to do the same thing. Sub For extDemo3 () Set MyRange = Range("A1:A100") For Each cell in MyRange If cell.Value > 0 Then cell.Font.Bold = True End if ext cell End Sub
http://www.xlpert.com/vba_index.htm
11/17
4/13/2011
G
GoTo (back to top) When the GoTo syntax is use, you can make Excel VBA to jump to a label and execute the line of code under the label like the On Error GoTo example I've demonstrate above. Let's look at another example... Sub GotoDemo () x = Int(Rnd() * (1 - 10) + 10) If x < 5 Then GoTo Less Else GoTo More End If Exit Sub Less: MsgBox x & " is less than 5" Exit Sub More: MsgBox x & " is more than 5" End Sub You can also specify a Excel macro to go to a specific range by using the GoTo method. For example, in a worksheet you have name a Range ("Credit Card"). To select this Range use the following statement... Sub GoToDemo2 () Application.Goto Reference:="Credit Card" End Sub 'a random number between 1 and 10
Goto Reference cell When you want to go to a specific cell or range, you can instruct Excel to do so by entering the code below... Private Sub Worksheet_SelectionChange(ByVal Target As Range) Application.Goto Reference:=Worksheets("Loan").Range("B100"), _ Scroll:=True End Sub As the Worksheet ("Loan") is activated, cell B100 will be at the top right window.
Your Ad Here
H
Height (back to top) To change the height userform, you can use the Height property. Look at the example below...
http://www.xlpert.com/vba_index.htm 12/17
Hiding Columns To hide a range of column the macro below will do the trick. Sub HideColDemo ( ) StartCol = 3 EndCol = 6 For n = StartCol to EndCol Columns(n).Hidden = True ext n End Sub With the above procedure column C to F will be hidden
Hiding Rows To hide a range of rows the macro below will do the trick. Sub HideRowDemo ( ) StartRow = 3 EndRow = 6 For n = StartRow to EndRow Rows(n).Hidden = True ext n End Sub With the above procedure Row 3 to 6 will be hidden
Hiding Sheets (back to top) You can use the following code to enable you to hide your worksheet from users. Name a worksheet Pharmacy. Sub HideSheetDemo()
Worksheets(Pharmacy).Visible = xlSheetVeryHidden
http://www.xlpert.com/vba_index.htm
13/17
If you hide your sheets this way, users will not be able to unhide them using the Excel menus. Only using VB codes will be able to display the sheets again.
Hide UserForm However, if you want to hide a userform different statement is required. The macro below will do the trick. If you have rename a userform to Account then the code is Sub HideUserformDemo () Account.Hide Range(A1).Value = Account.TextBox1.Text End Sub You still can access the value store in the userform programmatically. For example, you still can retrieve value on TextBox1 on the form.
Hyperlinks In Excel (back to top) You may notice that Excel automatically convert URL that you enter into hyperlink. If you don't like this then you can delete the hyperlink by entering the code below. Sub DeleteHyperLinksDemo() Sheet2.Hyperlinks.Delete End Sub Here all the hyperlinks in sheet 2 will be deleted
I
If Then statement This statement checks to see if a specific condition is true, and if true then it will execute all the code between the Then keyword and the End If statement. Look at the example below... Sub IfThenDemo ( ) Dim x As Integer, MySum As Integer For x = 1 to 100 If Is umeric(Range("A" & x)) = True Then MySum = MySum + Range("A" & x).Value End If ext x MsgBox MySum End Sub The above procedure will check whether the value in column A is numerical. If it is numerical, then it will add the cell value into MySum.
http://www.xlpert.com/vba_index.htm 14/17
4/13/2011
Input Box (back to top) Input Box is used to prompt user for input. The example below will ask the use to enter the year he is born and then a message box will display his age. Sub InputBoxDemo() MyInput = InputBox("Which year are you born?") Age = 2007 - MyInput
MsgBox "You are " & Age & " years old."
End Sub Let's look at another example... You can use the Input Box function to prompt specific user input during the execution of a subroutine. Look at the sample code below. Sub InputBoxDemo2 ( ) UserInput = InputBox("Type something", ,"Enter") End Sub A input box will be displayed asking the user to type something. The title of this input box is "Enter"
Inserting value into an existing cell that contain value Here you can use the Insert method. For example, cell A1 contain the word "Credit". You can insert another word "Card" by using the subroutine below. Sub InsertWordDemo ( ) Range("A1").Characters(8,4).Inserts("Card") End Sub You insert the word "Card" into cell A1 starting at character 8 with 4 character i.e "Card". As a result, cell A1 now contain the word "Credit Card".
Intersect (back to top) You can specify the location where two ranges intersect by leaving a space between the two range definitions. For example, Range(A2:F5 D2:G6) specifies a range where the range of of cells A2 to F5 intersect with the range of cells D2 to G6. Sub IntersectDemo ( ) Range(A2:F5 D2:G6).Select Selection. ame = "Medicine" End Sub Range("D2:F5") is the intersection, will be selected and is name "Medicine".
http://www.xlpert.com/vba_index.htm
15/17
Automatically invoke a macro after entering data into a particular column. The example below will call the macro myProcedure when there is changes in Column 3. The code is insert into the Worksheet_Change () module. Private Sub Worksheet_Change(ByVal Target As Excel.Range) If Target.Column = 3 Then myProcedure End Sub Inserting a Worksheet Function into a Cell (back to top) To insert a worksheet function into a cell, you specify the function as the value of the Formula property of the corresponding Range object. The following example insert the AVERAGE worksheet function into the property of range A1 on Sheet1 in the active workbook. Sub InsertFormulaDemo() Worksheets("Sheet1").Range("A1 ").Formula = "=AVERAGE( )" End Sub
If / Then / Else You use the If-Then structure when you want to execute one or more statements conditionally. The optional Else clause, enable you to execute one or more statements if the condition youre testing is false. See the example below... Sub IfThenElseDemo () If Time < 0.5 Then MsgBox "Good Morning" Else MsgBox "Good Afternoon" End Sub When Time is less than 0.5, it mean that it is before 12 pm.
Is umeric (back to top) This syntax enable to check a specified varaibles whether it is a numerical data. The subroutine below will check each cell in range A1:A100 whether it is a numerical value. If yes then it will be added to the total sum. Sub Is umericDemo ( ) Total = 0 For Each cell in Range("A1:A100") If Is umeric(cell.Value) Then Total = Total + cell.Value End If ext cell MsgBox Total
http://www.xlpert.com/vba_index.htm 16/17
http://www.xlpert.com/vba_index.htm
17/17