Excel VBA By Index (2)
Previous | Table of Contents | Next
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
J
| Joint two strings To joint two string, you can use the following example... Sub JointStringsDemo ( ) aStr = "fish" bStr = "miles' dStr = Left(aStr,2) eStr = Right(bStr,3) MsgBox dStr & eStr End Sub A message will display the word "files" in this case as the first two alphabets of "fish" is joint with the last three alphabets of "miles"
|
| Killing A File
Killing a file is equivalent to deleting file. It is easy to implement However the files you are killing must not be in used. For example you want to delete the file “Demo.xls” in your C drive stored in folder My Documents Sub Killfile()
L Left Function (back to top)This example below uses the Left function to return a specified number of characters from the left side of a string. Sub LeftFunctionDemo ()
List Box (back to top) This is how you populate a ListBox with items.Insert a Userform in your VBE. Add a ListBox on the UserForm. Activate the Userform_Initialize code window and enter the statement below... Private Sub UserForm_Initialize()
To determine which item you've selected then enter the following code in the ListBox_Change event code window.. Private Sub ListBox1_Change()
Lower Case (back to top) This example show you how to change text in a selected range to lower case . Sub ChangeLowerCaseDemo ()
Looping through a range of cells Sometimes you need to run the same block of statements on each cell in a range of cells. To do this, you must combine a looping statement and one or more methods to identify each cell, one at a time, and run the operation. Let use the statement For Each / next to do this. Sub LoopDemo ( ) Dim myRange as Range Set myRange = Range(“A1:A100”) For Each cell in myRange If Not cell.HasFormula Then cell.Value = 100 Next cell The above procedure will loop through every cell in Range(“A1:A100”). If the activecell contain no formula, the procedure will enter the value into 100 it.
Make Excel speak (back
to top)
Menus Collection (back to top) Let me show you how to add a new menu to a menu bar. The macro below will do the trick... Sub AddMenuDemo()
This will add a new menu "MyMenu" to the Menu bar before the Help menu. Then a sub menu "GoToDemo" is created. When you select "GoToDemo" it will call the procedure, "MyProcedure".
Message Box To be used to display message to the user and prompt action from the user as well. Sub MessageBoxDemo () Message = "Do you want to continue? " Ans = MsgBox(Message, vbYesNo, "Proceed?") If Ans = vbYes Then MyProcedure End Sub The above macro ask the user whether to continue with code execution. If user select yes then the macro will call the procedure MyProcedure, else it will end the program.
Month Function (back to top) This function is use to obtain the month value from a specified date... Sub MonthDemo MyDate = #October 15, 2007# MyMonth = Month(MyDate) 'result is 10 End Sub
Move Method Use this statement when you want to move around the worksheets in your workbook. The macro below will move Sheet 2 after Sheet 3 Sub MoveSheetDemo ( )
Name (back to top) The name properties is very easy to implement. Add a worksheet and change the name of a worksheet programmatically with the following code... Sub NameDemo () Worksheets.Add.Name = "Personal" End Sub
NOW Function This Excel VBA default function to show the Date and time. You can assign the result of this function to a variable, worksheet cell or a message box like the one below... Sub NowDemo()
Not The Not statement is used when you to toggle a certain properties for example... Sub NotDemo()
OffSet (back to top) The OffSet method enable you to define a range that is a specific offset from another range with the offset being the distance, in row and column. Sub OffSetDemo () Range("C2").Select ActiveCell.OffSet(1,1).Value = 100 'This will enter the value 100 into cell D3 ActiveCell.OffSet(-1,-1).Value = 200 'This will enter the value 200 into cell B1 Range(ActiveCell, ActiveCell.OffSet(2,2)).Select 'C2:E4 is selected End Sub
OnKey Method The OnKey method enable you to assign a specific key to a certain procedure. The following example demonstrate this... Sub OnKeyDeom ( ) Application.OnKey "^p", "MyProcedure" End Sub When you press Ctrl + p, Excel VBA will execute the subroutine MyProcedure.
OnTime (back to top) You can create a macro that execute at a specific time by using this OnTime event. With the example below, the code will execute "MyProcedure" after 10 seconds. Private Sub Worksheet_Activate()
Open Method The Open method is very useful whenever you need to run a specify macro when the workbook is open. The procedure below will run the macro Test in module 1 whenever the workbook is open.
Opening a document (back to top)To open document with Excel VBA, the following example using the Open Method will do the trick…
This statement above opens the file "C:\My Documents\Bet.doc" for editing. To open a Excel file as read only, enter the code below...
Password (back to top) The procedure below allows you to password protect a specific worksheet so that other user cannot modify it. Sub PasswordDemo() User will need to enter the correct password to edit the Worksheet "Health".
Placing formula in cell To insert a formula in a cell, the formula must be expressed in A1-style notation, and must include a leading equal sign. Look at the example below... Sub FormulaDemo ( ) Range("A1").Formula = "=Sum(A2:A3)" Range("B2").Formula = "=Avearage(C1:C100)" End Sub You can also put the exact same formula in each cell, by using an array, as in: Range("A1:C1").Formula = _ Array("=Sum(A2:A3)", "=Sum(A2:A3)", "=Sum(A2:A3)")
Protecting Worksheets (back to top) The procedure below demonstrate how you protect all the worksheets in a workbook. A For/Next statement is used to loop through all the worksheets... Sub ProtectSheetDemo() And to unprotect simply... Sub UnprotectSheetDemo()
Protecting A Chart Excel VBA enable user to protect a chart to prevent errors caused by someone attempting to change a protected chart. You can also password protect them. Let me show you an example. Sub ProtectChartDemo ( ) Charts(1).Protect Password = "Sweet Home", DrawingObjects:=False End Sub This will prevent anybody from modifying Chart 1 until the password is enter correctly. To unprotect insert the following code. Sub UnProtectChart()
Quit When you close all workbooks, you may notice that Excel is still running. If you want to close Excel altogether, then you can use the Quit method with the Application object. Sub QuitDemo () Application.Quit End Sub
Random Number (back to top) The procedure below will generate a random with the upper and lower value determine by the user, something like the Excel built-in function RANDBETWEEN( ). The code in this procedure takes this format : Int ((upperbound - lowerbound +1) * Rnd + lowerbound). Where the Upperbound is the largest number random number to be generated and Lowerbound is the lowest. Sub RandDemo ( ) UpperValue = 10 LowerValue = 0 r = Int((UpperValue - LowerValue + 1) * Rnd + LowerValue) Range("A1").Value = r End Sub Here a random number between 0 to 10 will be generated.
Range (back to top) You can use the Range object represents a group of one or more contiguous cells in an Excel worksheet. It is extremely useful, as it allows us to manipulate the properties of an individual cell or collection of cells in a worksheet. You will probably find yourself using the Range object in every program you write using VBA for the Excel application. Consider the following code examples that use properties of the Range object. Range(“B1”).Value=”Column B” Range(“B1:G1”).Columns.AutoFit Range(“B1:C1”, “E1:F1”).Font.Bold = True Let's combine 2 ranges together by using the Union method. The code below will combine 2 ranges into one and will set the font size to 8 if the cell value is a number... Sub RangeDemo()
Rectangle (back to top) The following statement adds a rectangle to the Worksheet named "Personal"... Sub RectangleDemo () WorkSheets("Personal").Rectangles.Add 150, 50, 50, 100 End Sub
Replace (back to top) Sometimes we need to replace certain words or a number that we have entered on a worksheet. It may be troublesome to look for the word or number one by one. You can actually write an Excel VBA procedure to do this and the macro below will do the trick. Sub ReplaceDemo () Dim sht As Worksheet
For Each Sht In Worksheets
sht.Cells.Replace What:="Home Loan", _
Replacement:="Mortgage", LookAt:=xlPart, MatchCase:=False
Next
End Sub
The procedure will loop through all the worksheets in the specify workbook, look for the word "Home Loan" and replace it with the word "Mortgage' Resizing the Height of Rows (back to top) You can specify the height of row/s with the Height property. Below is a procedure to set the height of a few rows.
Sub RowHeightDemo ( )
RowHeight = 15
For n = 1 to 10
ActiveSheet.Rows(n).Height = RowHeight
Next n
End Sub
Here the height of row 1 to 10 is set to 15 points.
Resume execution if an Error is encountered
You can ask Excel VBA to continue running even if an error is encounter. Just insert the code at the top of your subroutine like below.
Sub ResumeOnError ( )
Dim x As Integer
On Error Resume Next
x = "abc"
End Sub
Here x is assigned as an integer value. As "abc" is a string valuable, this subroutine will encounter an error. However since we have enter the syntax,
"On Error Resume Next" at the top, the subroutine will continue running.
|