Sunteți pe pagina 1din 9

VBA, Basic Excel Macro collection

http://www.panzerbasics.com/index_files/97-excel/basic-macros.htm

Alt + F11 to go VBA editor

Being a beginner at VBA programming myself, I need to


archive the ones I tried and found useful myself. Putting
them online was only a small step further.
If you run a Macro, the action can not be undone. Using the macros provided here is at
your own risk!
Keep in mind that Macros can be very useful, but also very dangerous if coming from an
unknown source.

The codes for these basic macros came from all over the internet or have been found by myself.
Since these are very common and basic, I did not bother mentioning sources. Should someone
recognise work of his own here and needs a name to be mentioned or the code removed, please
contact me.
The macros shown here are my own selection and should do to get started or help you out on
basic projects. Use your imagination to adjust them to fit in your project, or search for more info
on the internet.

The codes here have been tried and verified to work on my Excel 2007 Version. Please note that
it is often possible to reach the same goal in a different way.

Macros usually start with the line: "Sub Name()", where Name can be replaced by any name you
assign to it. Macros end with the line "End Sub".
For clarity and ease of use testing different ones, I left these lines out unless they differ for some
reason.
If in the above, "Sub" is replaced with "Function", the code works the same, but the macro does
not appear in the list of available macros. The downside of this method is that the function will
appear in the functions list.(Generally used for calculations and returning a value.) I sometimes
prefer this to keep overview in the macros list. If "Private" is used before "Sub" or "Function", it
can only be called from the same module, whilst also not being visible in the list.

Beware that the code shown on this page is made to look correct on your screen. Using
copy/paste may result in not working code because some characters have been replaced because
of the xhtml code
For example: a shown "&" on this page will show as "&" when copied.
Description Code Remarks
myRow = ActiveCell.Row
Active Cell,
myCol = ActiveCell.Column Shows Active Cell position.
Position
MsgBox myRow & "," & myCol
Selection.End(xlToLeft).Select The top one takes the active
Active Cell, cell to the far left, but not if
Selection to far OR there is an empty cell in
left between. To counter that the
Range("A" & ActiveCell.Row).Select bottom one works better.
With ActiveWindow
Active Cell in Scrolls to place the ActiveCell
.ScrollColumn = ActiveCell.Column
top left of be at the top & left of the
.ScrollRow = ActiveCell.Row
screen screen
End With
Active Cell, Shows the value of the current
MsgBox ActiveCell.Value
Value active cell
Making your macros run
automatically when opening
Sub Auto_Open() your workbook. This macro
Auto Run (1) MsgBox "Hello" will display the message
End Sub "Hello" when you open the
workbook. This code would
be located in the module.
For this second method,
Sub Workbook_Open()
giving the same result as the
Auto Run (2) MsgBox "Hello"
previous one, the code must
End Sub
be in the workbook.
Sub Worksheet_Activate()
This one starts on activating a
Auto Run (3) MsgBox "Hello"
sheet.
End Sub
This workbook: ' = Autorun
Sub Workbook_Open()
Call SaveMe
End Sub

In Module: Saves the file every 15 min in


Auto Save
Sub SaveMe() this case.
ThisWorkbook.Save
Application.OnTime Now +
Timeserial(0,15,0),"SaveMe" '
Timeserial=(h,m,s)
End Sub
Here we go to the bottom line
ActiveSheet.Range("A" & of the active sheet, then up on
(next)
ActiveSheet.Rows.Count).End(xlUp).Offset(1, the first row containing
Available Row
0).Select something in column "A" ,
then one down again.
The use of the "Call" keyword
is optional. And it may be
used for readability of your
Call -
Call Macro2 'This calls for Macro2 to run code.
Running a
within your Macro There is a catch... Using
subroutine
"Call" requires possible
arguments to be enclosed in
parentheses.
Dim cell As Range
For Each cell In Selection.Cells
If cell.HasFormula = False Then Upper case first letter of each
Case Title
cell = Application.Proper(cell) word in text.
End If
Next
Dim cell As Range
For Each cell In Selection.Cells To change text in a selected
Case Upper / If cell.HasFormula = False Then range to upper case, or if you
Lower cell = UCase(cell) want lower case, replace
End If UCase with LCase.
Next
Dim MyColumn As String, Here As String
Here = ActiveCell.Address
Shows the column letter(s)
Column Letters MyColumn = Mid(Here, InStr(Here, "$") + 1,
from the active cell.
InStr(2, Here, "$") - 2)
MsgBox MyColumn
myRows = Selection.Rows.Count
Counting Rows myColumns = Selection.Columns.Count Showing the number of Rows
& Columns MsgBox "Rows = " & myRows & vbCrLf & and Columns in a selection.
"Colums = " & myColumns
Carriage Return MsgBox "Line 1" & vbCrLf & "Line 2" Splits text in two rows
Range("A1:B1").Copy You get this when recording
Range("A2").PasteSpecial the macro. Note the use of
Copy Range (1)
Paste:=xlPasteValues "Application.CutCopyMode =
Application.CutCopyMode = False False" to clear the memory
Copy data from Sheet1 to
Sheet2.
Sheet1.Range("A1:C1").Copy
Copy Range (2) Please note that unlike the
Destination:=Sheet2.Range("A1")
above copy example, there is
no need to clear the memory
by
"Application.CutCopyMode =
False"
Also note that a sheet has in
fact two names, both visible in
VBA properties. Prefer using
the "Sheet X" in VBA since the
visible one's name can be
changed.
Similar but even shorter to the
Sheet2.Range("A1:C1").Value =
Copy Range (3) above, this would be the
Sheet1.Range("A1:C1").Value
better way to Copy.
Range("A1") = Range("A1") + 1 Basic counter, using cell A1
to display the result. Here
OR adding 1 each time the macro
Counter
is used. The second code does
myCount = Range("a1") + 1 the same, but might
Range("a1") = myCount sometimes be less confusing.
Place this code into "This
Workbook" and it will place
Private Sub Workbook_BeforeSave(ByVal
the date and time when
SaveAsUI As Boolean, Cancel As Boolean)
Current Date saving.
Range("A1") = Now
This is handy for knowing
End Sub
you are working on the latest
version of a file.
The current region is a range
bounded by any combination
of blank rows and blank
columns.
CurrentRegion Sheet1.Range("A1").CurrentRegion.Select
Alternatively, check out
Available Row if the region
might contain empty rows or
columns.
Set tbl = ActiveCell.CurrentRegion
CurrentRegion Select Current Region without
tbl.Offset(1, 0).Resize(tbl.Rows.Count - 1,
without header header
tbl.Columns.Count).Select
On Error Resume Next Trapping errors are important
as users can do marvelous
OR things to mess up you macros.
Here you can use either of
Error Trapping
Sub Name() these 2 statements.
On Error Goto ErrorHandler1 The first statement will allow
... more lines of code the macro to continue the next
Exit Sub line of code upon hitting an
ErrorHandler1: error but the second statement
... code specifying action on error will run an alternative code
End Sub should there be an error.
File Name & Range("A1") = Displays the full file name
Path Application.ActiveWorkbook.FullName and path
See Deleting Empty Rows.
General advise is against
using for next loops since they
For, Next Loop
can slow things down
considerably. Try to find an
alternative if possible.
Goto (Code) See Error Trapping
Dim MyInput
Get user input during macro
Input Box MyInput = InputBox("Enter something")
execution.
Range("A1") = MyInput
If Range("B1") > 10 Then
Range("B2") = 10 To be used in more variations.
ElseIf Range("B2") > 5 Then Add or delete ElseIf and Else
If, Then
Range("B2") = 5 if need be.
Statement
Else Also see the "Select Case"
Range("B2") = 1 statement.
End If
myCol = Selection.Columns.Count - 1
n=0
For n = 0 To Selection.Rows.Count - 1
For i = 1 To myCol
ActiveCell.Offset(n, 0) = Join text on each row in a
Joining Text
ActiveCell.Offset(n, 0) & ActiveCell.Offset(n, selection.
i)
ActiveCell.Offset(n, i) = ""
Next i
Next n
Here three different MsgBox
MsgBox "Created by: Your Name here" styles are shown. The buttons
MsgBox "Different Icon", vbInformation can also be customised to
Message Box
MsgBox "Different Icon And Title", show The "OK" button, or the
vbExclamation, "Your warning message" "Yes / No" buttons .(Refer to
vbYesNo macro)
Allow users to switch from
your form to the spreadsheet
Modeless
UserForm.show vbModeless by clicking on either one.
Forms
Usually, this is set beforehand
in the properties window.
Thought it might be useful to
mention here also.
(1, 0) = Down 1, (-1, 0) = Up
Offset ActiveCell.Offset(1, 0).Select 1, (0, 1) = Right 1 and finally,
(0, -1) = Left one
'Protect
Dim Password
Password = "xxxx"
ActiveSheet.Protect Password, True, True,
True
Protecting / This macro will
'Unprotect
Unprotecting a protect/unprotect the current
Password = "xxxx"
sheet worksheet with a password.
ActiveSheet.UnProtect Password

'Protect, but allow changes by VBA:


Sheet1.Protect Password:="xxxx",
UserInterfaceOnly:=True:
Sheet1.EnableSelection = xlNoRestrictions
For macros to generate
random numbers within
limits, use this code: Int
((upperbound - lowerbound
+1) * Rnd + lowerbound).
Random MyNumber = Int((10 - 1 + 1) * Rnd + 1) Where the Upperbound is the
numbers Range("A1") = MyNumber largest number random
number to be generated and
Lowerbound is the lowest.
In the left example code, the
random numbers that will be
generated range from 1 to 10.
Rounding Rounds to two digits behind
ActiveCell = Application.round(ActiveCell, 2)
Numbers the comma.
Save your Workbook
Saving your
ActiveWorkbook.Save automatically after running a
Workbook
Macro.
"False" Ensures the screen
does not flicker whilst
ScreenUpdating Application.ScreenUpdating = False / True running the macro. Don't
forget to set to "True" at the
end.
Select Case Range("A1").Value
Select Case Similar to the "If, Then"
Case 100, 150 ' = 100 OR 150
statement statement, "Select Case"
Range("B1").Value = Range("A1").Value
Case 200 To 300, 400 To 500 ' = Between statement is sometimes to be
200 and 300 OR between 400 and 500 preferred for better view.
Range("B2").Value = Range("A1").Value
Case Else
Range("B1").Value = 0
End Select
Dim myLastRow As Long
Dim myLastColumn As Long
Range("A1").Select
On Error Resume Next
myLastRow = Cells.Find("*", [A1], , , This is useful when you need
Select Data
xlByRows, xlPrevious).Row to select the whole range of
Range
myLastColumn = Cells.Find("*", [A1], , , your data.
xlByColumns, xlPrevious).Column
myRange = "a1:" & Cells(myLastRow,
myLastColumn).Address
Range(myRange).Select
To hide your worksheet from
users you can use this code.
Hiding your sheets this way,
prevents users to unhide them
using the menus. Only using
VBA codes will be able to
Sheets Hiding Sheet1.Visible = xlSheetVeryHidden
display the sheets again.
If you want to remain able to
make the sheet visible again
from the menus, use
something like this:
Sheet1.Visible = False
MsgBox Left("abcd", 2) 'Displays 2 characters
from Left
Here are some useful text
MsgBox Right("abcd", 2) 'Displays 2
Text Edit functions which you could use
characters from Right
to EDIT your text.
MsgBox Len("abcd") 'Displays number of
characters (Including space)
Timer puts a delay in
Application.Wait Now +
executing your code, but
Timer 1 TimeValue("00:00:05")
displays an hourglass during
MsgBox ("This was a 5 second delay")
the time.
After the set time, Macro2 is
Application.OnTime Now +
Timer 2 executed. This code does not
TimeValue("00:00:02"), "Macro2"
show the hourglass.
YesNo = MsgBox("This macro will ... Do you
vbYesNo Users need to click Yes or No
want to continue?", vbYesNo + vbCritical,
"Caution")
Select Case YesNo
Case vbYes
'Insert your "Yes" code here.
Case vbNo
'Insert your "No" code here.
End Select

If the Macros are for your own use, security is usually no problem. However, if you make a
Workbook and macros to be used by others, you will find that anything that can go wrong, will
go wrong. This means that security needs to get some serious attention. The following is usually
needed at least then:
1) Hide sheets that are not needed for view by the users
2) Protect your Workbook and Sheets with passwords
3) Protect your VBA code: Point at your project in the explorer window, right click on it and
select VBA project properties, click on the Protection tab, check on Lock Project for Viewing
and next key in your password.

Please keep in mind that I am an occasional user of Excel and VBA, which is the reason I made
this overview.
In case you need to contact me about it: rob@panzerbasics.com

S-ar putea să vă placă și