Saturday, August 22, 2009

MS Excel Macro For Beginners

Excel Macros (VBA) tips for beginners.
I hope the this site gets you started in Macro Programming & Good Luck.
Special Thanks to Julian's Macro Trip Site.
-----------------------------
To open Visual basic editor press __Alt + F11__ after you open excel work book.
-----------------------------
__Auto Run__%%%

Making your macros run automatically when opening your workbook. You can either use the Auto Open method or the Workbook Open method. These macros will display the message "Hello" when you open the workbook.

Sub Auto_Open()
Msgbox "Hello"
End Sub

This code would be located in the module. However if you use the second method, the code must be in the workbook (double click "This Workbook" in the explorer window). Click on the drop down list (that says General) and select Workbook. Click on the drop down list (that says declarations) and select Open.%%%


Private Sub Workbook_Open()
Msgbox "Hello"
End Sub
---------------------------
__Counting Rows & Columns & Sheets__%%%

When 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 columns
MsgBox myCount
End Sub%%%


The next macro counts the number of sheets instead.%%%


Sub Count2()
myCount = Application.Sheets.Count
MsgBox myCount
End Sub
---------------------------
__Close All Files__%%%

Sometimes 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 = False
myTotal = Workbooks.Count
For i = 1 To myTotal
ActiveWorkbook.Close
Next i
End Sub
--------------------------
__Copying A Range__%%%

Copy data from a specific range can be done with this macro. Here data is copied from the current sheet to the activecell. (Refer to Active Cell)%%%


Sub CopyRange()
Range("A1:A3").Copy Destination:=ActiveCell
End Sub%%%


To 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
-----------------------------
__Counter__ %%%

To 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") = mycount
End Sub
------------------------------
__Current Date__%%%


Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Range("A1") = Now 'Select any cell you want
End Sub
-------------------------------

No comments: