This document provides examples of using VBA code to select ranges and cells in Excel. Some key examples include:
1. Using Range, Cells, Columns, and Rows to select individual cells, ranges of cells, entire columns, and rows.
2. Examples of selecting cells by offsetting from a starting cell or range by rows and columns.
3. Using methods like Resize, Offset, SpecialCells to modify existing ranges and selections.
4. Looping through cells and ranges to perform actions on individual cells like formatting.
5. Examples of finding last used cells, counting cells with values, and using Find.
2. Fast Track in Excel
Range("A2").Select.................................................10
Range("A2:B3").Select...........................................10
.................................................................................10
Range("A2:C3 , A1:D2").Select..............................10
'union selection........................................................10
.................................................................................10
Range("B2,C4, D5:F25,G10").Select......................10
'Selecting multi range..............................................10
Range(Cells(1, 1), Cells(3, 3)).Select......................10
'This will select:.......................................................10
.................................................................................10
Range("A1", Range("Sales5")).Select.....................10
'select form cell A1 down to range Named "Sales5"...
10
Cells(5, "C").select 'this will select C5....................10
'To Select the active used range in the whole sheet10
Active Range is form the first cell you used to the
last cell.....................................................................10
In the whole active sheet.........................................10
ActiveSheet.UsedRange.Select...............................10
.................................................................................10
'To select the active range only for selected area use:.
10
ActiveCell.CurrentRegion.Select............................10
.................................................................................10
'This example will select the ranges that contain
numbers...................................................................10
Dim rng As Range...................................................10
Set rng =
ActiveSheet.Cells.SpecialCells( _xlCellTypeConstan
ts, xlNumbers).........................................................10
'count the number of cells that contain numbers.....10
Rng.select ' select the range.....................................10
'This example will select the ranges that contains
blank........................................................................10
Range("A1:D10").SpecialCells(xlCellTypeBlanks).S
elect.........................................................................10
Range("A1:A3").EntireRow.Select.........................10
ActiveCell.EntireRow.Delete..................................10
Range("C4").End(xlToRight).Select.......................10
'one cells will be selected........................................10
.................................................................................10
Range("A1048576").End(xlUp).Select...................11
'xlUp 'xlToRight 'xlToLeft 'xlDown.....................11
Range("A1" , Selection.End(xlToRight)).Select...11
'this will select the first row.....................................11
.................................................................................11
Range(Selection, Selection.End(xlDown)).Select...11
'This will selct form 1st row down to last row........11
.................................................................................11
'or.............................................................................11
Range("A1",
Range("A1").End(xlToRight).End(xlDown)).Select. .
11
Range("A1").Dependents.Select.............................11
Range("A1").DirectDependents.Select...................11
Range("A1:B2").Offset(1, 1).Select........................11
'This will select the same range shifted by 1 row
And by 1 Col...........................................................11
'EX1.........................................................................11
Set rng = Range("D2")............................................11
Rng.value =10 ' Now D2 =10..................................11
For i = 1 To 100.......................................................11
rng.Offset(0, i).Select..............................................11
If rng.Offset(0, i).Value <> I then...........................11
Rng.offset(0,i).Value = 20.......................................11
'EX2.........................................................................11
With ActiveCell.......................................................11
.offset(1,1).select.....................................................11
'Select one cell down and right according to the
active cell.................................................................11
.Offset(1).Select.......................................................11
'Select one cell down according to the active cell
(Note that offset by column is omitted here)...........11
End With..................................................................11
'EX2.........................................................................11
Range(ActiveCell.Offset(1),
ActiveCell.End(xlDown)).Select.............................11
................................................................................11
Range("A1:B2").Resize(4, 4).Select.......................11
'resize the range to A1:D4.......................................11
Selection.Resize(Selection.Rows.Count + 1).Select...
11
'Increases the current selection by one row.............11
'Note that column is omitted here(resize row only)11
Range("A1:B10").Resize(, 3).Select 'note that we
omit rows (column will changed only)....................11
'Resize database (Named table)...............................11
With Range("Database").........................................11
.Resize(.Rows.Count + 1).Name = "Database".......11
End With..................................................................11
'columns count and number.....................................11
Set rng = Range("C1:E1, G1:K1")..........................11
Rng.entirecolumn.select..........................................11
X = rng.Column.......................................................11
'x equal (2).............................................................11
'this code return the location of the first column....11
Y = rng.Columns.Count..........................................11
'Y equal (3)............................................................11
'this return the count of columns.............................11
'note that only the first partition of the range is
considered................................................................11
.................................................................................11
'To select specific rows or column use....................12
Columns(5).Select...................................................12
2
3. Columns("E").Select...............................................12
Columns("A:D").Select...........................................12
Rows("1:3").Select..................................................12
'Columns("C:D", "G:H") is error.............................12
'Thus use Union.......................................................12
Set rng = Union(Rows(3), Rows(5), Rows(7)).......12
'to know what is the last row?.................................12
lastRow =
Application.CountA(Sheets(1).Columns("A:A")). .12
'or.............................................................................12
LastRow = Range("A1").CurrentRegion.Rows.Count
12
CurntCol = ActiveWindow.ScrollColumn..............12
CurntRow = ActiveWindow.ScrollRow..................12
'the value of the postion of the current row will be
saved in curntRow...................................................12
Activewindow.ScrollRow = 150.............................12
'Active sheet will bw scrolled down to row 150.....12
'To loop through all rows.........................................12
For Each xRow In Range("A1", "D10").Rows.......12
xRow.Select.............................................................12
Next.........................................................................12
'Smart way to DeleteRows......................................12
Dim xRow As Long................................................12
‘Freeze screen..........................................................12
Application.ScreenUpdating = False.......................12
'Process rows from last row up to row (1)...............12
For xRow = Cells(Rows.Count,
"C").End(xlUp).Row To 1 Step -1.....................12
'Rows.count will return totlal number of rows in
Excel.......................................................................12
'Delete rows with value "Hi" in column C..............12
If Cells(xRow, "C").Value = "Hi " Then.................12
Cells(lRow, "C").EntireRow.Delete........................12
End If.......................................................................12
Next lRow................................................................12
Rows(5).Cells(2).Select...........................................12
'select the 2nd cell in row 5.....................................12
Range("C3")(-1, -1).Select......................................12
Range("C3").Cells(-1, -1).Select.............................12
'Select Shifted cell by (-1,-1) according to cell "C3". .
12
'i.e: Cells "A1" will be selected...............................12
Range("A1:B2").Cells(1, 1).Select..........................12
'Select cell shifted by (1,1) according to the 1st cell
in the range "A1".....................................................12
'i.e: Cell A1 will be selected....................................12
Set rng = Columns(3)..............................................12
rng.Range("A2").Select..........................................12
'Select Cell A2 acordign to "rng"............................12
'i.e Cell C2 will be selected.....................................12
rng.Cells(4).Select...................................................12
'cell number 4 with refrence to rng (ie.column 3)...12
'Examples:...............................................................12
Set rng = Range("A1:C5").Cells............................12
." 'cells" is optional (default case).........................12
rng(2).Select............................................................12
'will select the 2nd cell in the previous range..........12
Set rng = Range("A1:C5").columns........................12
Rng(2).select............................................................12
'Will select the 2nd column in rng...........................12
Set rng = Range("A1:C5").Rows............................12
Rng(2).select............................................................12
'Will select the 2nd row on the range......................12
Range("B1").Interior.ColorIndex = 1......................12
.................................................................................12
Cells(1,1).Interior.color = RGB(i, x, z)...................12
For Each Rng In Selection.Cells.............................12
Rndo = [=RANDBETWEEN(1,50)].......................12
Rng.Characters(1, InStr(Rng.Value, " ") -
1).Font.ColorIndex = Rndo.....................................12
Next.........................................................................12
'Charrcter return a set of characters, Characters(start,
End).........................................................................12
'inStr Returns the position of the 1st occurrence of
one string within another.........................................12
Dim oCell As Range................................................13
For Each oCell In Selection.Cells...........................13
If (oCell.Row Mod 2) = 1 Then..............................13
'i.e for odd row number..........................................13
oCell.Interior.ColorIndex = 3 ' red..........................13
Else..........................................................................13
'i.e for even row number.........................................13
oCell.Interior.ColorIndex = 5 ' blue........................13
End If.......................................................................13
Next.........................................................................13
Columns("A").ColumnWidth = 3............................13
Range("A1").IndentLevel = 3.................................13
Range("E1:G1").Merge...........................................13
If cells(1,1).value < 10 Then...................................13
Cells(1,1).Font.ColorIndex = 3...........................13
ElseIf cells(1,1).value < 100 Then..........................13
Cells(1,1).Font.ColorIndex = 5..............................13
Else..........................................................................13
Cells(1,1).Font.ColorIndex = 3............................13
End If...................................................................13
'If statement can be used on single line...................13
If rna.value = 1 Then rng.delete Else rng.
Font.ColorIndex = 15..............................................13
'EX...........................................................................13
Dim oCell as Range.................................................13
For i = 1 To Selection.Count...................................13
Set oCell = Selection.Cells(i).................................13
'Note: selection.cells(1) is the 1st cell in selection..13
If oCell.value > 100 Then........................................13
oCell.Font.ColorIndex = 3.......................................13
End If.......................................................................13
Next i...............................................................13
3
4. 'loop through the cell of range SalesData...............13
'loop 1......................................................................13
Set rngSales = Range("SalesData").........................13
For xRow = 1 To rngSales.Rows.Count..................13
For xColumn = 1 To rngSales.Columns.Count.......13
If rngSales.Cells(xRow, xColumn).Value < 100
Then.........................................................................13
'or you can write rngSales(xRow, xColumn)..........13
rngSales.Cells(xRow, xColumn).Font.ColorIndex =
3...............................................................................13
Else..........................................................................13
rngSales.Cells(xRow,xColumn).Font.ColorIndex= 1.
13
End If.......................................................................13
Next xColumn.........................................................13
Next xRow...............................................................13
'loop 2......................................................................13
For lCell = 1 To rngSales.Count.............................13
If rngSales(lCell).Value < 100 Then.......................13
rngSales(lCell).Font.ColorIndex = 3.......................13
Else..........................................................................13
rngSales(lCell).Font.ColorIndex = 1.......................13
End If.......................................................................13
Next lCell................................................................13
'loop3 (FOR EACH)................................................14
Dim rng As Range...................................................14
For Each rng In Range("SalesData").......................14
If rng.Value < 100 Then..........................................14
rng.Font.ColorIndex = 6..........................................14
Else..........................................................................14
rng.Font.ColorIndex = 1..........................................14
End If.......................................................................14
Next rng...................................................................14
'you can write:.........................................................14
ActiveCell.Formula = "=NOW()"...........................14
ActiveCell.NumberFormat = "dd/mm/yy"..............14
ActiveCell.Font.Name = "Arial".............................14
ActiveCell.Font.Bold = True...................................14
ActiveCell.Font.Size = 14.......................................14
'or.............................................................................14
With ActiveCell.......................................................14
.Formula = "=NOW()"............................................14
.NumberFormat = "dd/mm/yy"...............................14
.Font.Name = "Arial"..............................................14
.Font.Bold = True....................................................14
.Font.Size = 14.........................................................14
End With..................................................................14
'or even....................................................................14
With ActiveCell.......................................................14
.Formula = "=NOW()"............................................14
.NumberFormat = "dd/mm/yy"...............................14
With .Font................................................................14
.Name = "Arial".......................................................14
.Bold = True............................................................14
.Size = 14.................................................................14
End With..................................................................14
End With..................................................................14
'The above code will work only on active worksheet.
14
'To work on any sheet use "with"............................14
With Sheets("Sheet1").............................................14
.Range(.Cells(1, 1), .Cells(10, 5)).Font.Bold = True. .
14
End With..................................................................14
'Current date............................................................14
mydate = Date.........................................................14
'Current date and time..............................................14
myNow = Now........................................................14
'Current time............................................................14
myTime = Time.......................................................14
MyStr = Format(MyTime, "h:m:s") ' Returns
"17:4:23"..................................................................14
MyStr = Format(MyTime, "hh:mm:ss AMPM") '
Returns "05:04:23 PM"...........................................14
MyStr = Format(MyDate, "dddd, mmm d yyyy")14
'Returns Saturday, Jun 6 2009,...............................14
'Datepart...................................................................14
Sec = DatePart("s", Time)......................................14
'return current second..............................................14
'Also.........................................................................14
'yyyy Year................................................................14
'q Quarter.................................................................14
'm Month..................................................................14
'y Day of year..........................................................14
'd Day.......................................................................14
'w Weekday.............................................................14
'ww Week................................................................14
'h Hour.....................................................................14
'n Minute..................................................................14
's Second..................................................................14
'Date diff..................................................................14
TheDate = InputBox("Enter a date").......................14
Diff = DateDiff("d", Now, TheDate)......................14
'dateDiff: return diffrenace of given date and now
date in terms of day.................................................14
'Date Add.................................................................14
TheDate = InputBox("Enter a date").......................14
New date = DateAdd("m", 5, FirstDate).................14
'add 5 monthes to TheDate......................................14
GetChoice = Choose(2, "Speedy", "United",
"Federal")................................................................14
'Return Speedy.........................................................14
Evaluate...................................................................14
x = Evaluate("=ISBLANK(A1)")............................14
'or simply.................................................................14
x = [ISBLANK(A1)]...............................................14
'You can put any Excel formula in between these two
bracket []..................................................................14
4
5. ]A1] = 10................................................................14
'set value in cell "A1" to 10.....................................14
Set rng = Range("A1:D10")....................................14
rMin = Application.workSheetFunction.Min(rng)..14
XSum = Application.workSheetFunction.Sum(rng)...
14
On Error Resume Next............................................14
Vlook =
Application.workSheetFunction.Vlookup("f",
Range("A1:B5"), 2, False)......................................14
Range("A1:B2").Sort Key1:=Rows(1),
Orientation:=xlSortColumns...................................15
Dim c As Range......................................................15
For Each c In [A1:C5].............................................15
If c.Value Like "A*" Then......................................15
c.Font.Bold = True..................................................15
End If.......................................................................15
Next.........................................................................15
Set rng = Range("A1:A12").Find(What:="Jun", _..15
LookAt:=xlWhole, LookIn:=xlValues)...................15
'Return a set of cells that differ from certain range.15
Set r1 =
ActiveSheet.Columns("A").ColumnDifferences( _15
Comparison:=ActiveSheet.Range("A4"))...........15
r1.Select...................................................................15
'This example selects the cells in column A on
Sheet1 whose contents are different from cell A4...15
Set rng = Range("B2")............................................15
x = rng.Address(ReferenceStyle:=xlA1).................15
'Returns $B$2........................................................15
x = rng.Address(ReferenceStyle:=xlA1,
External:=True)......................................................15
'Returns [Book1]Sheet1!$B$2................................15
Do Until x = 5.........................................................15
x = x + 1...................................................................15
If x = 2 Then............................................................15
Exit Do....................................................................15
End If.......................................................................15
Loop.........................................................................15
---------------------.....................................................15
Dim x As Boolean...................................................15
Dim i As Integer......................................................15
x = True...................................................................15
i = 1..........................................................................15
Do While x..............................................................15
x = IsEmpty(ActiveSheet.Rows(1).Cells(i))...........15
i = i + 1....................................................................15
Loop.........................................................................15
------------------.........................................................15
Sub ShadeEverySecondRow()................................15
Range("A2").EntireRow.Select...............................15
Do While ActiveCell.Value <> ""...........................15
Selection.Interior.ColorIndex = 15..........................15
ActiveCell.Offset(2, 0).EntireRow.Select...............15
Loop.........................................................................15
End sub....................................................................15
.................................................................................15
Sub ShadeEverySecondRowV2()............................15
Dim lRow As Long.................................................15
lRow = 2..................................................................15
Do Until IsEmpty(Cells(lRow, 1))..........................15
Cells(lRow,1).EntireRow.Interior.ColorIndex= 15.15
lRow = lRow + 2.....................................................15
Loop.........................................................................15
End Sub...................................................................15
'OnErrorGoTo..........................................................15
Sub ErrorHand1()....................................................15
On Error GoTo ERR_EXAMPLE...........................15
X = Range(A1)/Range(A2).....................................15
'in case the above code return error the code will go
to label.....................................................................15
"ERR_EXAMPLE".................................................15
Don't forget the exit sub before the labels...............15
Exit Sub...................................................................15
ERR_EXAMPLE:...................................................15
MsgBox Err.Description, vbCritical.......................15
End Sub...................................................................15
'OnErrorResum-Case1.............................................15
On Error Resume Next............................................15
X = Range(A1)/Range(A2).....................................15
If Err.Number <> 0 Then........................................15
MsgBox Err.Description, vbCritical.......................15
End If.......................................................................15
'turn on Error handling again...................................15
On Error GoTo 0.....................................................15
'OnErrorResum-Case2.............................................15
On Error GoTo ERR_EXAMPLE...........................15
X = Range(A1)/Range(A2).....................................15
Y = Y + 1.................................................................15
Exit Sub...................................................................16
ERR_EXAMPLE:...................................................16
MsgBox Err.Description, vbCritical.......................16
Resume Next...........................................................16
End Sub...................................................................16
'OnErrorResum-Case3.............................................16
Dim sNew As String................................................16
sNew = "a:test.xls".................................................16
On Error GoTo ERR_DISK....................................16
Workbooks.Open sNew...........................................16
Exit Sub...................................................................16
ERR_DISK:.............................................................16
If Err.Number = 1004 Then.....................................16
sNew = InputBox("Cannot find file. Enter new
location or leave blank to").....................................16
If sNew <> "" Then.................................................16
Resume....................................................................16
'NOTE THAT..........................................................16
5
6. 'Resume: will resume the code where the error
happened (i.e: workbooks.open).............................16
'Resume next: will resume the code a line after the
code happened.......................................................16
Else..........................................................................16
Exit Sub...................................................................16
End If...................................................................16
End If...................................................................16
End Sub...................................................................16
Mark = InputBox("Enter ur mark").........................16
Select Case Mark.....................................................16
Case Is > 90.............................................................16
MsgBox "Very good"..............................................16
Case Is > 70.............................................................16
MsgBox "good".......................................................16
Case Is < 50.............................................................16
MsgBox "Fail".........................................................16
Case Else.................................................................16
MsgBox "else".........................................................16
End Select................................................................16
X = range("A1").value.............................................16
Resullt = Switch(x > 90, "Very good", _................16
X > 75, "good", _.....................................................16
x < 50, "Failed")......................................................16
ThisWorkbook.Worksheets("hi").Activate.............16
ThisWorkbook.Worksheets("hi").Copy..................16
X =Worksheets.Count.............................................16
Worksheets("hi").Delete..........................................16
ActiveSheet.ScrollArea = "A1:B200".....................16
'To Clear scroll area.................................................16
ActiveSheet.ScrollArea = ""....................................16
Filename = "c:pic.jpg"............................................16
Worksheets("hi").SetBackgroundPicture (Filename)..
16
'Rename all worksheets...........................................16
Dim Wks As Object................................................16
For Each wks In workSheets...................................16
wks.Name = "Hi" & wks.Index...............................16
Next wks..................................................................16
'loop through ceartin sheets.....................................16
Sub FormatGroup().................................................16
Dim shts As Sheets..................................................16
Dim wks As Worksheet...........................................16
Set shts = workSheets(Array(1, 3, 5)).....................16
For Each wks In shts...............................................16
wks.Range("A1").Value = 100................................16
Next wks..................................................................16
End Sub...................................................................16
Workbooks.Add......................................................16
ActiveWorkbook.SaveAs
Filename:="C:DataSalesData1.xlsx"....................16
ActiveWorkbook.SaveAs Filename:="C:
SalesData2.xlsx"......................................................16
Workbooks("SalesData1.xlsx").Activate................16
'this is better you can track the workbook without
saving.......................................................................16
Dim wkb1 As Workbook........................................16
Dim wkb2 As Workbook........................................16
Set wkb1 = Workbooks.Add...................................16
Set wkb2 = Workbooks.Add...................................16
wkb1.Activate..........................................................16
wkb1.SaveAs Filename:="c:test.xlsx"...................16
Nm = wkb1.Name...................................................16
Pth = wkb2.path.......................................................16
----............................................................................16
'EX1.........................................................................16
Dim wbs As Workbooks.........................................16
Set wbs = Application.Workbooks..........................16
C = wbs.Count.........................................................16
x = ActiveWorkbook.Name....................................17
Workbooks(x).Activate...........................................17
'WorkbookObject.Close(SaveChanges, FileName)17
i = ThisWorkbook.FullName..................................17
----............................................................................17
Set wkb = Workbooks.Add.....................................17
wkb.SaveAs Filename:="JanSales.xlsx".................17
'EX2.........................................................................17
On Error GoTo errfile..............................................17
WKname = "C:Data.xls"........................................17
Workbooks.Add......................................................17
ActiveWorkbook.SaveAs Filename:=WKname.....17
ActiveWorkbook.Close...........................................17
Exit Sub...................................................................17
'If name exist delete it..............................................17
errfile:......................................................................17
Kill WKname..........................................................17
Resume Next...........................................................17
'EX3.........................................................................17
'Loop to open multi Workbooks.............................17
Dim avData As Variant, wkb As Workbook...........17
Dim i As Integer......................................................17
avData = Array("North", "South", "East", "West").17
For i = LBound(avData) To UBound(avData)........17
Set wkb = Workbooks.Open(Filename:=avData(i) &
".xls").......................................................................17
'Process data here.....................................................17
wkb.Close SaveChanges:=True...............................17
Next i.......................................................................17
Dim x(3) As Integer...............................................17
x(0) = 1....................................................................17
x(1) = 3....................................................................17
x(2) = 8....................................................................17
x(3) = 5...................................................................17
Ave = (x(0) + x(1) + x(2) + x(3)) / 3.......................17
'quick array..............................................................17
MyWeek = Array("Mon", "Tue", "Wed", "Thu",
"Fri", "Sat", "Sun")..................................................17
'2D array..................................................................17
6
7. Dim avData(1 To 10, 1 To 20)................................17
Arr = Range("A1:A3").Value..................................17
X = Arr (1 , 1) 'Value in Cell A1.............................17
'EX2.........................................................................17
Dim celARR(1 To 100) As Range..........................17
UB = UBound(celARR)..........................................17
For i = 1 To UB.......................................................17
Set celARR(i) = Cells(i, i).......................................17
celARR(i).Font.Bold = True...................................17
Next i.......................................................................17
'EX3.........................................................................17
aiData = Range("A1:A20").Value...........................17
Dim sMessage As String.........................................17
Dim i As Integer......................................................17
For i = LBound(aiData) To UBound(aiData)..........17
aiData(i,1) = i..........................................................17
Next i.......................................................................17
'Note.........................................................................17
vData = Range("A2:F10000").Value......................17
'it is array................................................................17
Set rngData = Range("A2:F10000")......................17
'it is Range...............................................................17
'i.e if:........................................................................17
rngData(1,1)= 1000.................................................17
'then cells A1 will take value 1000..........................17
'EX:process data in array.........................................17
Dim MarksTable As Variant...................................17
Dim vFail() As Variant............................................17
Dim i As Long.........................................................17
'Assign range values to array...................................17
MarksTable = Range("A1:F50").Value...................17
Total_student =
WorksheetFunction.CountA(MarksTable)..............17
ReDim vFail(1 To UBound(MarksTable, 1), 1 To 1).
17
'Process data in the array.........................................17
For i = 1 To UBound(MarksTable, 1).....................17
If MarksTable(i, 6) < 50......................................17
And MarksTable(i, 6) > 0....................................17
Then.........................................................................17
vFail(i, 1) = "Fail"...................................................17
End If.......................................................................17
Next i.......................................................................17
'Write array values back to the worksheet...............17
Range("G2").Resize(UBound(MarksTable,1),1).Val
ue=vFail...................................................................17
Total_Fail = WorksheetFunction.CountA(vFail)....17
vMonths = Array("Jan", "Feb", "Mar", "Apr",
"May", "Jun", _........................................................17
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec").............17
'add iteam to combo box "AddItem" method..........18
For i = LBound(vMonths) To UBound(vMonths). .18
activesheet.ComboBox1.AddItem vMonths(i)........18
Next i.......................................................................18
.................................................................................18
'To clear items:........................................................18
ComboBox1.Clear...................................................18
'paste this code in the sheets code...........................18
Private Sub OptionButton1_Click()........................18
Call options..............................................................18
End Sub...................................................................18
Private Sub OptionButton2_Click()........................18
Call options..............................................................18
End Sub...................................................................18
Private Sub OptionButton3_Click()........................18
Call options..............................................................18
End Sub...................................................................18
'''''''''...........................................................................18
Public Sub options()................................................18
With ActiveSheet....................................................18
Select Case True......................................................18
Case .OptionButton1.Value.....................................18
MsgBox "Option buttom 1 is selected"...................18
Case .OptionButton2.Value.....................................18
MsgBox "Option buttom 2 is selected"...................18
Case .OptionButton3.Value.....................................18
MsgBox "Option buttom 3 is selected"...................18
End Select................................................................18
End With..................................................................18
End Sub...................................................................18
.................................................................................18
'insert formula array into ranges..............................18
Range("A1:C11").formulaArray = "=A1:C3 +
A5:C7".....................................................................18
Worksheets("Sheet1").Columns("A").Parse _........18
parseLine:="[xxx] [xxx] [xxx]", _.......................18
Destination:=Worksheets("Sheet1").Range("B1")..
18
FillDown..................................................................18
Range("C1:C15").FillDown....................................18
Range("A1:B1").AutoFill Range("A1:B10"),
xlFillSeries...............................................................18
'Enum XlAutoFillType............................................18
'xlFillDefault = 0.....................................................18
'xlFillCopy = 1.........................................................18
'xlFillSeries = 2........................................................18
'xlFillFormats = 3....................................................18
'xlFillValues = 4......................................................18
'xlFillDays = 5.........................................................18
'xlFillWeekdays = 6.................................................18
'xlFillMonths = 7.....................................................18
'xlFillYears = 8........................................................18
'xlLinearTrend = 9...................................................18
'xlGrowthTrend = 10...............................................18
'End Enum...............................................................18
Range("A1:C3").Copy Range("H5").......................18
Range("A1:C3").Cut Range("D5").........................18
Range("A1:B3").Copy Destination:=Range("G4").18
7
8. Dim rng As Range...................................................18
Set rng = Range("B3").............................................18
rng.AddComment ("your comment here")..............18
rng.ClearComments.................................................18
'Or............................................................................18
Dim c As Comment.................................................18
Set c = rng.AddComment("your comment here")...18
c.Visible = True.......................................................18
c.Shape.AutoShapeType = msoShapeCloudCallout...
18
'Or............................................................................18
If Range("A1").Comment Is Nothing Then............18
Range("A1").AddComment "comment".................18
End If.......................................................................19
Range("A1").Comment.Text "Created: " & Now...19
Range("A1").Comment.Visible = True...................19
'RangeObject.AutoFilter(Field, Criteria1, Operator,
Criteria2).................................................................19
Range("A1:B10").AutoFilter 2, "1997", xlOr, "1998"
19
With ActiveSheet.Outline........................................19
.SummaryRow = xlAbove.......................................19
.AutomaticStyles = True..........................................19
End With..................................................................19
With ActiveSheet....................................................19
.Rows("6:10").Group...............................................19
.Rows("12:15").Group.............................................19
.Rows("17:20").Group.............................................19
End With..................................................................19
Application.DisplayAlerts = False..........................19
Application.ScreenUpdating = False.......................19
Application.Calculation = xlCalculationManual....19
Application.Calculation = xlCalculationAutomatic19
With
Application.FileDialog(msoFileDialogFolderPicker).
19
.Show.......................................................................19
'Display path...........................................................19
Path = .SelectedItems(1)..........................................19
End With..................................................................19
'This command is a file open dialog........................19
'4parm:..................................................................19
'1-msoFileDialogFilePicker.................................19
'2-msoFileDialogFolderPicker.............................19
'3-msoFileDialogOpen.........................................19
'4-msoFileDialogSaveAs.....................................19
'Listing files with a For..Each loop..........................19
Dim objFSO As Object...........................................19
Dim objFolder As Object........................................19
Dim objFile As Object............................................19
'Create a reference to the FileSystemObject............19
Set objFSO =
CreateObject("Scripting.FileSystemObject")..........19
'Create a folder reference.........................................19
Set objFolder = objFSO.GetFolder("C:windows")...
19
'List files in folder....................................................19
For Each objFile In objFolder.Files........................19
i = i + 1....................................................................19
Cells(i, 2) = objFile.Name.......................................19
Next objFile.............................................................19
Const Red = 3..........................................................19
Selection.Interior.ColorIndex = Red.......................19
Public X...................................................................19
Static Y....................................................................19
'use "static" to extend variable life time.................19
'use "public" to extend variable to all procedure....19
Dim AnyDate As Date............................................19
AnyDate = #6/25/1994 1:20:00 PM#......................19
startTime = Time.....................................................19
For i = 1 To 10000...................................................19
If IsEmpty(Cells(i, 1)) Then....................................19
Rows(i).Delete.........................................................19
End If.......................................................................19
Next.........................................................................19
Endtime = Time.......................................................19
calcTime = Format(Endtime - startTime, "h:m:s").19
MsgBox "ok done in: " & calcTime........................19
Sub test()..................................................................19
Call ProcedureB1....................................................19
End Sub...................................................................19
Sub ProcedureB1()..................................................19
Dim x As Integer.....................................................19
x = 5........................................................................19
End Sub...................................................................19
Sub callFun()...........................................................19
Call ChangeFormatting("Arial Narrow", 24)..........19
'OR-----....................................................................19
ChangeFormatting FontName:="Arial Narrow",
FontSize:=24...........................................................19
End Sub...................................................................19
Sub ChangeFormatting(FontName As String, _.....19
Optional FontSize As Variant)................................19
'Change font name..................................................19
Selection.Font.Name = FontName..........................19
'Change font size if argument is supplied................19
If Not IsMissing(FontSize) Then............................19
Selection.Font.Size = CInt(FontSize)......................19
End If.......................................................................19
End Sub...................................................................19
Function Fahrenheit(Centigrade)............................19
Fahrenheit = Centigrade * 9 / 5 + 32.......................19
End Function...........................................................20
Application.ScreenUpdating = False.......................20
'Find a cell containing Test Word............................20
Set rngFoundCell = Range("C:C").Find(What:="Test
Word").....................................................................20
'Keep looping until no more cells found.................20
8
9. Do Until rngFoundCell Is Nothing..........................20
'Delete found cell row..............................................20
rngFoundCell.EntireRow.Delete.............................20
'Find next.................................................................20
Set rngFoundCell = Range("C:C").FindNext..........20
Loop.........................................................................20
Private Sub Workbook_Open()...............................20
Sheets("Main").Activate..........................................20
With Application....................................................20
.DisplayFullScreen = True..................................20
.CommandBars("Full Screen").Visible = False...20
.CommandBars("Worksheet Menu
Bar").Enabled=False...............................................20
.CommandBars("Standard").Visible = False.......20
.CommandBars("Formatting").Visible = False...20
.CommandBars("Drawing").Visible = False.......20
.CommandBars("Reviewing").Visible = False....20
.CommandBars("Web").Visible = False.............20
.DisplayStatusBar = False...................................20
.DisplayFormulaBar = False................................20
End With................................................................20
End Sub...................................................................20
?Range("B2").Value...............................................20
'this will print the result immediately......................20
Application.StatusBar ="Macro working now"......20
Application.StatusBar = False.................................20
'open the note pad and write in................................20
dReturnValue = Shell("NOTEPAD.EXE",
vbNormalFocus)......................................................20
'The following code will run "my procecdure" after
15 sec.......................................................................20
Application.OnTime Now + TimeValue("00:00:15"),
"my_Procedure"......................................................20
Sub RefreshData()...................................................20
ThisWorkbook.UpdateLink Name:="C:Data.xlsx",
Type:=xlExcelLinks................................................20
CycleTime = Now + TimeSerial(0, 0, 5).................20
'Refresh data each 5 sec...........................................20
Application.OnTime CycleTime, "RefreshData"....20
End Sub...................................................................20
Sub StopRefresh()...................................................20
Application.OnTime CycleTime, "RefreshData", ,
False.........................................................................20
End Sub...................................................................20
..............................................................................20
Sub AssignDown()..................................................20
Application.OnKey "{Down}", "DownTen"..........20
End Sub...................................................................20
Sub DownTen().......................................................20
ActiveCell.Offset(10000, 0).Select.........................20
End Sub...................................................................20
Sub ClearDown().....................................................20
Application.OnKey "{Down}"................................20
End Sub...................................................................20
'The function will be recalculated whenever
calculation occurs in any cells.................................20
Function getX().......................................................20
Application.Volatile................................................20
x = worksheets("1").range("a1").............................20
End Function...........................................................20
'Use dir to check if function exist............................20
Function bFileExists(sFile As String) As Boolean.20
If Dir(sFile) <> "" Then bFileExists = True............20
End Function...........................................................20
'this insert empty rows at each week change...........20
Sub ShowWeeks()...................................................20
Dim iToday As Integer............................................20
Dim iYesterday As Integer......................................20
'Insert empty rows between weeks..........................20
Range("A2").Select.................................................20
iYesterday = Weekday(ActiveCell.Value)..............20
'Loop until an empty cell is found...........................20
Do Until IsEmpty(ActiveCell.Value)......................21
'Select cell below.....................................................21
ActiveCell.Offset(1, 0).Select.................................21
'Calculate day of week from date in cell.................21
iToday = Weekday(ActiveCell.Value)....................21
'If day index has decreased, insert row....................21
If iToday < iYesterday Then...................................21
ActiveCell.EntireRow.Insert...................................21
ActiveCell.Offset(1, 0).Select.................................21
End If.......................................................................21
'Store latest week day index....................................21
iYesterday = iToday................................................21
Loop.........................................................................21
End Sub...................................................................21
TypeName...............................................................21
'return the type of the object....................................21
x = TypeName(Sheet1)...........................................21
'this will return worksheet or chart…......................21
x = typename("selection").......................................21
'this will return Range ,object or picture …............21
'defining names........................................................21
Names.Add Name:="Data", RefersTo:="=Sheet1!
$D$10:$D$12".........................................................21
'or.............................................................................21
Names.Add Name:="Sheet1!Sales",
RefersTo:="=Sheet1!$E$10:$E$12".......................21
'or.............................................................................21
'Range("A1:D10").Name = "SalesData".................21
'to give name for range............................................21
rng.Name = "Data"..................................................21
'to give name for string............................................21
Dim v As Variant....................................................21
v = 3.14159..............................................................21
Names.Add Name:="StoreNumber", RefersTo:=v.21
'to give a formual a name........................................21
9
10. 'Names.Add Name:="ItemsInA",
RefersTo:="=COUNTA($A:$A)"...........................21
'to give array a name................................................21
Dim aiArray(1 To 200, 1 To 3) As Integer.............21
Names.Add Name:="MyName", RefersTo:=aiArray.
21
'to give name to an array by using evaluate.............21
NewArray = [MyName]..........................................21
• Track 1: Ranges & Selection
The most important feature in VBA_Excel is to
select Ranges
There are many way to Select Ranges:
Basic Range selection:
Range("A2").Select
Range("A2:B3").Select
Range("A2:C3 , A1:D2").Select
'union selection
Range("B2,C4, D5:F25,G10").Select
'Selecting multi range
Range(Cells(1, 1), Cells(3, 3)).Select
'This will select:
Range("A1", Range("Sales5")).Select
'select form cell A1 down to range Named "Sales5"
Cells(5, "C").select 'this will select C5
Select active region
'To Select the active used range in the whole sheet
Active Range is form the first cell you used to the last cell
In the whole active sheet
ActiveSheet.UsedRange.Select
'To select the active range only for selected area use:
ActiveCell.CurrentRegion.Select
Select Special
'This example will select the ranges that contain numbers
Dim rng As Range
Set rng =
ActiveSheet.Cells.SpecialCells( _xlCellTypeConst
ants, xlNumbers)
'count the number of cells that contain numbers
Rng.select ' select the range
'This example will select the ranges that contains blank
Range("A1:D10").SpecialCells(xlCellTy
peBlanks).Select
Select Entire
Range("A1:A3").EntireRow.Select
ActiveCell.EntireRow.Delete
Select XLEnd
Range("C4").End(xlToRight).Select
'one cells will be selected
10
11. Range("A1048576").End(xlUp).Select
'xlUp 'xlToRight 'xlToLeft 'xlDown
Range("A1" ,
Selection.End(xlToRight)).Select
'this will select the first row
Range(Selection,
Selection.End(xlDown)).Select
'This will selct form 1st
row down to last row
'or
Range("A1",
Range("A1").End(xlToRight).End(xlDo
wn)).Select
Select dependents
Range("A1").Dependents.Select
Range("A1").DirectDependents.Select
Offset range
Range("A1:B2").Offset(1, 1).Select
' This will select the same range shifted by 1 row And by 1 Col
'EX1
Set rng = Range("D2")
Rng.value =10 ' Now D2 =10
For i = 1 To 100
rng.Offset(0, i).Select
If rng.Offset(0, i).Value <> I then
Rng.offset(0,i).Value = 20
'EX2
With ActiveCell
.offset(1,1).select
'Select one cell down and right according to the active cell
.Offset(1).Select
'Select one cell down according to the active cell (Note that
offset by column is omitted here)
End With
'EX2
Range(ActiveCell.Offset(1),
ActiveCell.End(xlDown)).Select
Resize Range
Range("A1:B2").Resize(4, 4).Select
'resize the range to A1:D4
Selection.Resize(Selection.Rows.Count + 1).Select
'Increases the current selection by one row
'Note that column is omitted here(resize row only)
Range("A1:B10").Resize(, 3).Select
'note that we omit rows (column will changed only)
'Resize database (Named table)
With Range("Database")
.Resize(.Rows.Count + 1).Name = "Database"
End With
Column and rows
'columns count and number
Set rng = Range("C1:E1, G1:K1")
Rng.entirecolumn.select
X = rng.Column
' x equal (2)
' this code return the location of the first column
Y = rng.Columns.Count
' Y equal (3)
'this return the count of columns
'note that only the first partition of the range is considered
11
12. 'To select specific rows or column use
Columns(5).Select
Columns("E").Select
Columns("A:D").Select
Rows("1:3").Select
'Columns("C:D", "G:H") is error
'Thus use Union
Set rng = Union(Rows(3), Rows(5), Rows(7))
'to know what is the last row?
lastRow =
Application.CountA(Sheets(1).Column
s("A:A"))
'or
LastRow =
Range("A1").CurrentRegion.Rows.Cou
nt
CurntCol = ActiveWindow.ScrollColumn
CurntRow = ActiveWindow.ScrollRow
' the value of the postion of the current row will be saved in
curntRow
Activewindow.ScrollRow = 150
'Active sheet will bw scrolled down to row 150
'To loop through all rows
For Each xRow In Range("A1", "D10").Rows
xRow.Select
Next
'Smart way to DeleteRows
Dim xRow As Long
‘Freeze screen
Application.ScreenUpdating = False
'Process rows from last row up to row (1)
For xRow = Cells(Rows.Count,
"C").End(xlUp).Row To 1 Step -1
'Rows.count will return totlal number of rows in Excel
'Delete rows with value "Hi" in column C
If Cells(xRow, "C").Value = "Hi " Then
Cells(lRow, "C").EntireRow.Delete
End If
Next lRow
Virtual range
Rows(5).Cells(2).Select
'select the 2nd
cell in row 5
Range("C3")(-1, -1).Select
Range("C3").Cells(-1, -1).Select
'Select Shifted cell by (-1,-1) according to cell "C3"
'i.e: Cells "A1" will be selected
Range("A1:B2").Cells(1, 1).Select
'Select cell shifted by (1,1) according to the 1st
cell in the range "A1"
'i.e: Cell A1 will be selected
Set rng = Columns(3)
rng.Range("A2").Select
'Select Cell A2 acordign to "rng"
'i.e Cell C2 will be selected
rng.Cells(4).Select
'cell number 4 with refrence to rng (ie.column 3)
'Examples:
Set rng = Range("A1:C5").Cells
' ".cells" is optional (default
case)
rng(2).Select
'will select the 2nd
cell in the previous range
Set rng = Range("A1:C5").columns
Rng(2).select
'Will select the 2nd column in rng
Set rng = Range("A1:C5").Rows
Rng(2).select
'Will select the 2nd
row on the range
• Track 2: Format Ranges
Coloring range
Range("B1").Interior.ColorIndex = 1
Cells(1,1).Interior.color = RGB(i, x, z)
Coloring Char
For Each Rng In Selection.Cells
Rndo = [=RANDBETWEEN(1,50)]
Rng.Characters(1, InStr(Rng.Value, " ") -
1).Font.ColorIndex = Rndo
Next
' Charrcter return a set of characters,
Characters(start, End)
'inStr Returns the position of the 1st
occurrence of one string
within another.
12
13. Color line yes line no
Dim oCell As Range
For Each oCell In Selection.Cells
If (oCell.Row Mod 2) = 1 Then
' i.e for odd row number
oCell.Interior.ColorIndex = 3 ' red
Else
' i.e for even row number
oCell.Interior.ColorIndex = 5 ' blue
End If
Next
Format Selected range in selected sheets
Dim Sht As Object
Dim sAddress As String
sAddress = Selection.Address
For Each Sht In
ActiveWindow.SelectedSheets
If TypeName(Sht) = "Worksheet" Then
Sht.Range(sAddress).Font.Bold =
True
End If
Next Sht
Misc formatting
Columns("A").ColumnWidth = 3
Range("A1").IndentLevel = 3
Range("E1:G1").Merge
• Track 3: Basic VBA commands
If statment
If cells(1,1).value < 10 Then
Cells(1,1).Font.ColorIndex = 3
ElseIf cells(1,1).value < 100 Then
Cells(1,1).Font.ColorIndex = 5
Else
Cells(1,1).Font.ColorIndex = 3
End If
'If statement can be used on single line
If rna.value = 1 Then rng.delete Else rng. Font.ColorIndex = 15
For loop
For I = 1 To 10
For J = 100 To 1 step -1
For K = 10 To 1 step -2
...
Next K
Next J
Next I
'EX
Dim oCell as Range
For i = 1 To Selection.Count
Set oCell = Selection.Cells(i)
'Note: selection.cells(1) is the 1st
cell in selection
If oCell.value > 100 Then
oCell.Font.ColorIndex = 3
End If
Next i
' loop through the cell of range SalesData
'loop 1
Set rngSales = Range("SalesData")
For xRow = 1 To
rngSales.Rows.Count
For xColumn = 1 To
rngSales.Columns.Count
If rngSales.Cells(xRow,
xColumn).Value < 100 Then
'or you can write rngSales(xRow, xColumn)
rngSales.Cells(xRow,
xColumn).Font.ColorIndex = 3
Else
rngSales.Cells(xRow,xColumn).Font.ColorIndex= 1
End If
Next xColumn
Next xRow
'loop 2
For lCell = 1 To rngSales.Count
If rngSales(lCell).Value < 100
Then
rngSales(lCell).Font.ColorIndex =
3
Else
rngSales(lCell).Font.ColorIndex =
1
End If
Next lCell
13
14. 'loop3 (FOR EACH)
Dim rng As Range
For Each rng In Range("SalesData")
If rng.Value < 100 Then
rng.Font.ColorIndex = 6
Else
rng.Font.ColorIndex = 1
End If
Next rng
With
'you can write:
ActiveCell.Formula = "=NOW()"
ActiveCell.NumberFormat = "dd/mm/yy"
ActiveCell.Font.Name = "Arial"
ActiveCell.Font.Bold = True
ActiveCell.Font.Size = 14
'or
With ActiveCell
.Formula = "=NOW()"
.NumberFormat = "dd/mm/yy"
.Font.Name = "Arial"
.Font.Bold = True
.Font.Size = 14
End With
'or even
With ActiveCell
.Formula = "=NOW()"
.NumberFormat = "dd/mm/yy"
With .Font
.Name = "Arial"
.Bold = True
.Size = 14
End With
End With
Range(Cells(1, 1), Cells(10, 5)).Select
'The above code will work only on active worksheet
'To work on any sheet use "with"
With Sheets("Sheet1")
.Range(.Cells(1, 1), .Cells(10, 5)).Font.Bold = True
End With
Date
'Current date
mydate = Date
'Current date and time
myNow = Now
'Current time
myTime = Time
MyStr = Format(MyTime, "h:m:s")
' Returns "17:4:23".
MyStr = Format(MyTime, "hh:mm:ss AMPM")
' Returns "05:04:23 PM".
MyStr = Format(MyDate, "dddd, mmm d yyyy")
'Returns Saturday, Jun 6 2009,
'Datepart
Sec = DatePart("s", Time)
'return current second
'Also
'yyyy Year
'q Quarter
'm Month
'y Day of year
'd Day
'w Weekday
'ww Week
'h Hour
'n Minute
's Second
'Date diff
TheDate = InputBox("Enter a date")
Diff = DateDiff("d", Now, TheDate)
'dateDiff: return diffrenace of given date and now date in terms
of day
'Date Add
TheDate = InputBox("Enter a date")
New date = DateAdd("m", 5, FirstDate)
'add 5 monthes to TheDate
Choice
GetChoice = Choose(2, "Speedy", "United", "Federal")
'Return Speedy
Evaluate
x = Evaluate("=ISBLANK(A1)")
'or simply
x = [ISBLANK(A1)]
'You can put any Excel formula in between these two bracket []
[A1] = 10
'set value in cell "A1" to 10
Worksheet Function
Set rng = Range("A1:D10")
rMin =
Application.workSheetFunction.Min(rng)
XSum =
Application.workSheetFunction.Sum(rng)
On Error Resume Next
Vlook =
Application.workSheetFunction.Vlookup("f",
Range("A1:B5"), 2, False)
Sort
14
15. Range("A1:B2").Sort Key1:=Rows(1),
Orientation:=xlSortColumns
Search
Dim c As Range
For Each c In [A1:C5]
If c.Value Like "A*"
Then
c.Font.Bold = True
End If
Next
Find
Set rng =
Range("A1:A12").Find(What:="Jun", _
LookAt:=xlWhole, LookIn:=xlValues)
ColumnDifferences
'Return a set of cells that differ from certain range
Set r1 =
ActiveSheet.Columns("A").ColumnDifference
s( _
Comparison:=ActiveSheet.Range("A4"))
r1.Select
'This example selects the cells in column A on Sheet1 whose
contents are different from cell A4.
Address
Set rng = Range("B2")
x = rng.Address(ReferenceStyle:=xlA1)
' Returns $B$2
x = rng.Address(ReferenceStyle:=xlA1, External:=True)
' Returns [Book1]Sheet1!$B$2
Do while
Do Until x = 5
x = x + 1
If x = 2 Then
Exit Do
End If
Loop
---------------------
Dim x As Boolean
Dim i As Integer
x = True
i = 1
Do While x
x = IsEmpty(ActiveSheet.Rows(1).Cells(i))
i = i + 1
Loop
------------------
Sub ShadeEverySecondRow()
Range("A2").EntireRow.Select
Do While ActiveCell.Value <> ""
Selection.Interior.ColorIndex = 15
ActiveCell.Offset(2, 0).EntireRow.Select
Loop
End sub
Sub ShadeEverySecondRowV2()
Dim lRow As Long
lRow = 2
Do Until IsEmpty(Cells(lRow, 1))
Cells(lRow,1).EntireRow.Interior.ColorIndex= 15
lRow = lRow + 2
Loop
End Sub
ONERROR
'OnErrorGoTo
Sub ErrorHand1()
On Error GoTo ERR_EXAMPLE
X = Range(A1)/Range(A2)
' in case the above code return error the code will go to label
"ERR_EXAMPLE"
Don't forget the exit sub before the labels
Exit Sub
ERR_EXAMPLE:
MsgBox Err.Description, vbCritical
End Sub
'OnErrorResum-Case1
On Error Resume Next
X = Range(A1)/Range(A2)
If Err.Number <> 0 Then
MsgBox Err.Description, vbCritical
End If
'turn on Error handling again
On Error GoTo 0
'OnErrorResum-Case2
On Error GoTo ERR_EXAMPLE
X = Range(A1)/Range(A2)
Y = Y + 1
15
16. Exit Sub
ERR_EXAMPLE:
MsgBox Err.Description, vbCritical
Resume Next
End Sub
'OnErrorResum-Case3
Dim sNew As String
sNew = "a:test.xls"
On Error GoTo ERR_DISK
Workbooks.Open sNew
Exit Sub
ERR_DISK:
If Err.Number = 1004 Then
sNew = InputBox("Cannot find file.
Enter new location or leave blank
to")
If sNew <> "" Then
Resume
'NOTE THAT
'Resume: will resume the code where the error happened (i.e:
workbooks.open)
'Resume next: will resume the code a line after the code
happened
Else
Exit Sub
End If
End If
End Sub
Case
Mark = InputBox("Enter ur mark")
Select Case Mark
Case Is > 90
MsgBox "Very good"
Case Is > 70
MsgBox "good"
Case Is < 50
MsgBox "Fail"
Case Else
MsgBox "else"
End Select
Switch
X = range("A1").value
Resullt = Switch(x > 90, "Very
good", _
X > 75, "good", _
x < 50, "Failed")
• Track 4: Wroksheet&workbook function
Worksheet
ThisWorkbook.Worksheets("hi").Activate
ThisWorkbook.Worksheets("hi").Copy
X =Worksheets.Count
Worksheets("hi").Delete
ActiveSheet.ScrollArea = "A1:B200"
'To Clear scroll area
ActiveSheet.ScrollArea = ""
Filename = "c:pic.jpg"
Worksheets("hi").SetBackgroundPicture (Filename)
'Rename all worksheets
Dim Wks As Object
For Each wks In workSheets
wks.Name = "Hi" & wks.Index
Next wks
'loop through ceartin sheets
Sub FormatGroup()
Dim shts As Sheets
Dim wks As Worksheet
Set shts = workSheets(Array(1, 3, 5))
For Each wks In shts
wks.Range("A1").Value = 100
Next wks
End Sub
Workbook
Workbooks.Add
ActiveWorkbook.SaveAs
Filename:="C:DataSalesData1.xlsx"
ActiveWorkbook.SaveAs
Filename:="C: SalesData2.xlsx"
Workbooks("SalesData1.xlsx").Activate
' this is better you can track the workbook without
saving
Dim wkb1 As Workbook
Dim wkb2 As Workbook
Set wkb1 = Workbooks.Add
Set wkb2 = Workbooks.Add
wkb1.Activate
wkb1.SaveAs
Filename:="c:test.xlsx"
Nm = wkb1.Name
Pth = wkb2.path
----
'EX1
Dim wbs As Workbooks
Set wbs = Application.Workbooks
C = wbs.Count
16
17. x = ActiveWorkbook.Name
Workbooks(x).Activate
'WorkbookObject.Close(SaveChanges, FileName)
i = ThisWorkbook.FullName
----
Set wkb = Workbooks.Add
wkb.SaveAs Filename:="JanSales.xlsx"
'EX2
On Error GoTo errfile
WKname = "C:Data.xls"
Workbooks.Add
ActiveWorkbook.SaveAs Filename:=WKname
ActiveWorkbook.Close
Exit Sub
'If name exist delete it
errfile:
Kill WKname
Resume Next
'EX3
' Loop to open multi Workbooks
Dim avData As Variant, wkb As Workbook
Dim i As Integer
avData = Array("North", "South", "East",
"West")
For i = LBound(avData) To UBound(avData)
Set wkb = Workbooks.Open(Filename:=avData(i) &
".xls")
'Process data here
wkb.Close SaveChanges:=True
Next i
• Track 5: Array
Dim x(3) As
Integer
x(0) = 1
x(1) = 3
x(2) = 8
x(3) = 5
Ave = (x(0) + x(1) + x(2) + x(3)) / 3
'quick array
MyWeek = Array("Mon", "Tue", "Wed",
"Thu", "Fri", "Sat", "Sun")
'2D array
Dim avData(1 To 10, 1 To 20)
Arr = Range("A1:A3").Value
X = Arr (1 , 1) 'Value in Cell A1
'EX2
Dim celARR(1 To 100) As Range
UB = UBound(celARR)
For i = 1 To UB
Set celARR(i) = Cells(i, i)
celARR(i).Font.Bold = True
Next i
'EX3
aiData = Range("A1:A20").Value
Dim sMessage As String
Dim i As Integer
For i = LBound(aiData) To UBound(aiData)
aiData(i,1) = i
Next i
'Note
vData = Range("A2:F10000").Value
'it is array
Set rngData = Range("A2:F10000")
'it is Range
'i.e if:
rngData(1,1)= 1000
'then cells A1 will take value 1000
'EX:process data in array
Dim MarksTable As Variant
Dim vFail() As Variant
Dim i As Long
'Assign range values to array
MarksTable = Range("A1:F50").Value
Total_student = WorksheetFunction.CountA(MarksTable)
ReDim vFail(1 To UBound(MarksTable, 1), 1 To 1)
'Process data in the array
For i = 1 To UBound(MarksTable, 1)
If MarksTable(i, 6) < 50
And MarksTable(i, 6) > 0
Then
vFail(i, 1) = "Fail"
End If
Next i
'Write array values back to the worksheet
Range("G2").Resize(UBound(MarksTa
ble,1),1).Value=vFail
Total_Fail =
WorksheetFunction.CountA(vFail)
• Track 6: Control
Combo_Box
vMonths = Array("Jan", "Feb", "Mar", "Apr",
"May", "Jun", _
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
17
18. 'add iteam to combo box "AddItem" method
For i = LBound(vMonths) To UBound(vMonths)
activesheet.ComboBox1.AddItem vMonths(i)
Next i
'To clear items:
ComboBox1.Clear
Option_buttom
'paste this code in the sheets code
Private Sub OptionButton1_Click()
Call options
End Sub
Private Sub OptionButton2_Click()
Call options
End Sub
Private Sub OptionButton3_Click()
Call options
End Sub
'''''''''
Public Sub options()
With ActiveSheet
Select Case True
Case .OptionButton1.Value
MsgBox "Option buttom 1 is
selected"
Case .OptionButton2.Value
MsgBox "Option buttom 2 is
selected"
Case .OptionButton3.Value
MsgBox "Option buttom 3 is
selected"
End Select
End With
End Sub
• Track 7: Misc
formulaArray
'insert formula array into ranges
Range("A1:C11").formulaArray =
"=A1:C3 + A5:C7"
ParseCloumn
Worksheets("Sheet1").Columns("A").P
arse _
parseLine:="[xxx] [xxx] [xxx]",
_
Destination:=Worksheets("Sheet1").R
ange("B1")
FillDown
Range("C1:C15").FillDown
Range("A1:B1").AutoFill
Range("A1:B10"), xlFillSeries
'Enum XlAutoFillType
'xlFillDefault = 0
'xlFillCopy = 1
'xlFillSeries = 2
'xlFillFormats = 3
'xlFillValues = 4
'xlFillDays = 5
'xlFillWeekdays = 6
'xlFillMonths = 7
'xlFillYears = 8
'xlLinearTrend = 9
'xlGrowthTrend = 10
'End Enum
Copy_Paste
Range("A1:C3").Copy Range("H5")
Range("A1:C3").Cut Range("D5")
Range("A1:B3").Copy Destination:=Range("G4")
Comment
Dim rng As Range
Set rng = Range("B3")
rng.AddComment ("your comment here")
rng.ClearComments
'Or
Dim c As Comment
Set c = rng.AddComment("your comment here")
c.Visible = True
c.Shape.AutoShapeType = msoShapeCloudCallout
'Or
If Range("A1").Comment Is Nothing
Then
Range("A1").AddComment "comment"
18
19. End If
Range("A1").Comment.Text "Created:
" & Now
Range("A1").Comment.Visible = True
AutoFilter
'RangeObject.AutoFilter(Field, Criteria1, Operator, Criteria2)
Range("A1:B10").AutoFilter 2, "1997", xlOr, "1998"
GroupRows
With ActiveSheet.Outline
.SummaryRow = xlAbove
.AutomaticStyles = True
End With
With ActiveSheet
.Rows("6:10").Group
.Rows("12:15").Group
.Rows("17:20").Group
End With
Disable / Enbale
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.Calculation =
xlCalculationAutomatic
Open Dialog box
With
Application.FileDialog(msoFileDialogFolderPicker)
.Show
' Display path
Path = .SelectedItems(1)
End With
'This command is a file open dialog
' 4 parm:
' 1- msoFileDialogFilePicker
' 2- msoFileDialogFolderPicker
' 3- msoFileDialogOpen
' 4- msoFileDialogSaveAs
List files name
'Listing files with a For..Each loop
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
'Create a reference to the
FileSystemObject
Set objFSO =
CreateObject("Scripting.FileSystemObject")
'Create a folder reference
Set objFolder =
objFSO.GetFolder("C:windows")
'List files in folder
For Each objFile In objFolder.Files
i = i + 1
Cells(i, 2) = objFile.Name
Next objFile
Constants
Const Red = 3
Selection.Interior.ColorIndex = Red
Public X
Static Y
' use "static" to extend variable life time
' use "public" to extend variable to all procedure
Date
Dim AnyDate As Date
AnyDate = #6/25/1994 1:20:00 PM#
DeleteEmptyRow
startTime = Time
For i = 1 To 10000
If IsEmpty(Cells(i, 1)) Then
Rows(i).Delete
End If
Next
Endtime = Time
calcTime = Format(Endtime - startTime, "h:m:s")
MsgBox "ok done in: " & calcTime
Procedure
Sub test()
Call ProcedureB1
End Sub
Sub ProcedureB1()
Dim x As Integer
x = 5
End Sub
Function
Sub callFun()
Call ChangeFormatting("Arial Narrow", 24)
'OR-----
ChangeFormatting FontName:="Arial Narrow", FontSize:=24
End Sub
Sub ChangeFormatting(FontName As
String, _
Optional FontSize As Variant)
' Change font name
Selection.Font.Name = FontName
'Change font size if argument is supplied
If Not IsMissing(FontSize) Then
Selection.Font.Size = CInt(FontSize)
End If
End Sub
Function Fahrenheit(Centigrade)
Fahrenheit = Centigrade * 9 / 5 + 32
19
20. End Function
Find
Application.ScreenUpdating = False
'Find a cell containing Test Word
Set rngFoundCell =
Range("C:C").Find(What:="Test Word")
'Keep looping until no more cells found
Do Until rngFoundCell Is Nothing
'Delete found cell row
rngFoundCell.EntireRow.Delete
'Find next
Set rngFoundCell =
Range("C:C").FindNext
Loop
Change to full secreen
Private Sub Workbook_Open()
Sheets("Main").Activate
With Application
.DisplayFullScreen = True
.CommandBars("Full Screen").Visible = False
.CommandBars("Worksheet Menu Bar").Enabled=False
.CommandBars("Standard").Visible = False
.CommandBars("Formatting").Visible = False
.CommandBars("Drawing").Visible = False
.CommandBars("Reviewing").Visible = False
.CommandBars("Web").Visible = False
.DisplayStatusBar = False
.DisplayFormulaBar = False
End With
End Sub
Using immediate window
?Range("B2").Value
'this will print the result immediately
Status Bar control
Application.StatusBar ="Macro working now"
Application.StatusBar = False
Send Key
'open the note pad and write in
dReturnValue = Shell("NOTEPAD.EXE", vbNormalFocus)
Schedule (OnTime)
'The following code will run "my procecdure" after 15 sec
Application.OnTime Now +
TimeValue("00:00:15"), "my_Procedure"
Sub RefreshData()
ThisWorkbook.UpdateLink
Name:="C:Data.xlsx",
Type:=xlExcelLinks
CycleTime = Now + TimeSerial(0, 0, 5)
'Refresh data each 5 sec
Application.OnTime CycleTime, "RefreshData"
End Sub
Sub StopRefresh()
Application.OnTime CycleTime, "RefreshData", , False
End Sub
Assign key
Sub AssignDown()
Application.OnKey "{Down}",
"DownTen"
End Sub
Sub DownTen()
ActiveCell.Offset(10000, 0).Select
End Sub
Sub ClearDown()
Application.OnKey "{Down}"
End Sub
Volatile
'The function will be recalculated whenever calculation occurs
in any cells
Function getX()
Application.Volatile
x = worksheets("1").range("a1")
End Function
Dir
'Use dir to check if function exist
Function bFileExists(sFile As
String) As Boolean
If Dir(sFile) <> "" Then
bFileExists = True
End Function
EXAMPLES
'this insert empty rows at each week change
Sub ShowWeeks()
Dim iToday As Integer
Dim iYesterday As Integer
'Insert empty rows between weeks
Range("A2").Select
iYesterday =
Weekday(ActiveCell.Value)
'Loop until an empty cell is found
20
21. Do Until IsEmpty(ActiveCell.Value)
'Select cell below
ActiveCell.Offset(1, 0).Select
'Calculate day of week from date in cell
iToday = Weekday(ActiveCell.Value)
'If day index has decreased, insert row
If iToday < iYesterday Then
ActiveCell.EntireRow.Insert
ActiveCell.Offset(1, 0).Select
End If
'Store latest week day index
iYesterday = iToday
Loop
End Sub
TypeName
'return the type of the object
x = TypeName(Sheet1)
'this will return worksheet or chart….
x = typename("selection")
'this will return Range ,object or picture ….
NAME
'defining names
Names.Add Name:="Data",
RefersTo:="=Sheet1!$D$10:$D$12"
'or
Names.Add Name:="Sheet1!Sales",
RefersTo:="=Sheet1!$E$10:$E$12"
'or
'Range("A1:D10").Name = "SalesData"
'to give name for range
rng.Name = "Data"
'to give name for string
Dim v As Variant
v = 3.14159
Names.Add Name:="StoreNumber",
RefersTo:=v
'to give a formual a name
'Names.Add Name:="ItemsInA",
RefersTo:="=COUNTA($A:$A)"
'to give array a name
Dim aiArray(1 To 200, 1 To 3) As
Integer
Names.Add Name:="MyName",
RefersTo:=aiArray
'to give name to an array by using evaluate
NewArray = [MyName]
21