SlideShare a Scribd company logo
Macro VBA Excel Page.1
Handout Macro VBA Excel
Loop
Looping is one of the most powerful programming techniques. A loop in Excel VBA enables you to loop through a
range of cells with just a few codes lines.
Single Loop
You can use a single loop to loop through a one-dimensional range of cells.
Place a command button on your worksheet and add the following code lines:
Dim i As Integer
For i = 1 To 6
Cells(i, 1).Value = 100
Next i
Result when you click the command button on the sheet:
Explanation: The code lines between For and Next will be executed six times. For i = 1, Excel VBA enters the
value 100 into the cell at the intersection of row 1 and column 1. When Excel VBA reaches Next i, it increases i
with 1 and jumps back to the For statement. For i = 2, Excel VBA enters the value 100 into the cell at the
intersection of row 2 and column 1, etc.
Note: it is good practice to always indent (tab) the code between the words For and Next. This makes your code
easier to read.
Double Loop
You can use a double loop to loop through a two-dimensional range of cells.
Place a command button on your worksheet and add the following code lines:
Dim i As Integer, j As Integer
For i = 1 To 6
Macro VBA Excel Page.2
Handout Macro VBA Excel
For j = 1 To 2
Cells(i, j).Value = 100
Next j
Next i
Result when you click the command button on the sheet:
Explanation: For i = 1 and j = 1, Excel VBA enters the value 100 into the cell at the intersection of row 1 and
column 1. When Excel VBA reaches Next j, it increases j with 1 and jumps back to the For j statement. For i = 1
and j = 2, Excel VBA enters the value 100 into the cell at the intersection of row 1 and column 2. Next, Excel VBA
ignores Next j because j only runs from 1 to 2. When Excel VBA reaches Next i, it increases i with 1 and jumps
back to the For i statement. For i = 2 and j = 1, Excel VBA enters the value 100 into the cell at the intersection of
row 2 and column 1, etc.
Triple Loop
You can use a triple loop to loop through two-dimensional ranges on multiple Excel worksheets.
Place a command button on your worksheet and add the following code lines:
Dim c As Integer, i As Integer, j As Integer
For c = 1 To 3
For i = 1 To 6
For j = 1 To 2
Worksheets(c).Cells(i, j).Value = 100
Next j
Next i
Next c
Explanation: The only change made compared to the code for the double loop is that we have added one more
loop and added Worksheets(c). in front of Cells to get the two-dimensional range on the first sheet for c = 1, the
second sheet for c = 2 and the third sheet for c = 3. Download the Excel file to see this result.
Do While Loop
Besides the For Next loop, there are other loops in Excel VBA. For example, the Do While Loop. Code placed
between Do While and Loop will be repeated as long as the part after Do While is true.
Macro VBA Excel Page.3
Handout Macro VBA Excel
1. Place a command button on your worksheet and add the following code lines:
Dim i As Integer
i = 1
Do While i < 6
Cells(i, 1).Value = 20
i = i + 1
Loop
Result when you click the command button on the sheet:
Explanation: as long as i is lower than 6, Excel VBA enters the value 20 into the cell at the intersection of row i
and column 1 and increments i by 1. In Excel VBA (and in other programming languages), the symbol '=' means
becomes. It does not mean equal. So i = i + 1 means i becomes i + 1. In other words: take the present value of i
and add 1 to it. For example, if i = 1, i becomes 1 + 1 = 2. As a result, the value 20 will be placed into column A
five times (not six because Excel VBA stops when i equals 6).
2. Enter some numbers in column A.
3. Place a command button on your worksheet and add the following code lines:
Dim i As Integer
i = 1
Do While Cells(i, 1).Value <> ""
Cells(i, 2).Value = Cells(i, 1).Value + 10
Macro VBA Excel Page.4
Handout Macro VBA Excel
i = i + 1
Loop
Result when you click the command button on the sheet:
Explanation: as long as Cells(i, 1).Value is not empty (<> means not equal to), Excel VBA enters the value into
the cell at the intersection of row i and column 2, that is 10 higher than the value in the cell at the intersection of
row i and column 1. Excel VBA stops when i equals 7 because Cells(7, 1).Value is empty. This is a great way to
loop through any number of rows on a worksheet.
Macro VBA Excel Page.5
Handout Macro VBA Excel
Loop through Defined Range
Below we will look at a program that loops through a defined range. For example, when we want to square the
numbers in Range("A1:A3"). Did you know you can also loop through a dynamic range?
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, we declare two Range objects. We call the Range objects rng and cell.
Dim rng As Range, cell As Range
2. We initialize the Range object rng with Range("A1:A3").
Set rng = Range("A1:A3")
3. Add the For Each Next loop.
For Each cell In rng
Next cell
Note: rng and cell are randomly chosen here, you can use any names. Remember to refer to these names in the
rest of your code.
4. Next, we square each cell in this range. To achieve this, add the following code line to the loop:
cell.Value = cell.Value * cell.Value
Result when you click the command button on the sheet:
Macro VBA Excel Page.6
Handout Macro VBA Excel
5. If you want to check each cell in a randomly selected range, simply replace:
Set rng = Range("A1:A3")
with:
Set rng = Selection
6. Now, for example select Range("A1:A2").
Result when you click the command button on the sheet:
Macro VBA Excel Page.7
Handout Macro VBA Excel
Loop through Entire Column
Below we will look at a program in Excel VBA that loops through the entire first column and colors all values that
are lower than a certain value.
Place a command button on your worksheet and add the following code lines:
1. First, declare a variable called i of type Long. We use a variable of type Long here because Long variables
have larger capacity than Integer variables.
Dim i As Long
2. Next, add the code line which changes the font color of all the cells in column A to black.
Columns(1).Font.Color = vbBlack
3. Add the loop.
For i = 1 To Rows.Count
Next i
Macro VBA Excel Page.8
Handout Macro VBA Excel
Note: worksheets can have up to 65,536 rows in Excel 2003 and up to 1,048,576 rows in Excel 2007 and Excel
2010. No matter what version you are using, the code line above loops through all rows (downloadable Excel file
is in Excel 97-2003 format).
4. Next, we color all values that are lower than the value entered into cell D2. Empty cells are ignored. Add the
following code lines to the loop.
If Cells(i, 1).Value < Range("D2").Value And Not IsEmpty(Cells(i, 1).Value) Then
Cells(i, 1).Font.Color = vbRed
End If
Result when you click the command button on the sheet (this may take a while):
Macro VBA Excel Page.9
Handout Macro VBA Excel
Do Until Loop
Although not used very often on this site, you might find yourself in a situation where you want to use the Do Until
Loop in Excel VBA. Code placed between Do Until and Loop will be repeated until the part after Do Until is true.
Place a command button on your worksheet and add the following code lines:
Dim i As Integer
i = 1
Do Until i > 6
Cells(i, 1).Value = 20
i = i + 1
Loop
Result when you click the command button on the sheet:
Explanation: until i is higher than 6, Excel VBA places the value 20 into the cell at the intersection of row i and
column 1 and increments i by 1. As a result, the value 20 will be placed into column A six times (not seven
because Excel VBA stops when i equals 7).
Macro VBA Excel Page.10
Handout Macro VBA Excel
Step Keyword
You can use the Step keyword in Excel VBA to specify a different increment for the counter variable of a loop.
1. Place a command button on your worksheet and add the following code lines:
Dim i As Integer
For i = 1 To 6 Step 2
Cells(i, 1).Value = 100
Next i
Result when you click the command button on the sheet:
Explanation: The code lines between For and Next will be executed three times. For i = 1, Excel VBA enters the
value 100 into the cell at the intersection of row 1 and column 1. When Excel VBA reaches Next i, it increases i
with 2 and jumps back to the For statement. For i = 3, Excel VBA enters the value 100 into the cell at the
intersection of row 3 and column 1, etc.
2. Place a command button on your worksheet and add the following code lines:
Dim j As Integer
For j = 8 To 3 Step -1
Cells(6, j).Value = 50
Next j
Result when you click the command button on the sheet:
Macro VBA Excel Page.11
Handout Macro VBA Excel
Explanation: The code lines between For and Next will be executed six times. For j = 8, Excel VBA enters the
value 50 into the cell at the intersection of row 6 and column 8. When Excel VBA reaches Next j, it decreases j
with 1 and jumps back to the For statement. For j = 7, Excel VBA enters the value 50 into the cell at the
intersection of row 6 and column 7, etc.
Macro VBA Excel Page.12
Handout Macro VBA Excel
Create a Pattern
Below we will look at a program in Excel VBA that creates a pattern.
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, we declare two variables of type Integer. One named i and one named j.
Dim i As Integer, j As Integer
2. Second, we add two For Next loops.
For i = 1 To 5 Step 2
For j = 1 To 5 Step 2
3. Next, we add the line which changes the background color of the cells to light gray.
Cells(i, j).Interior.ColorIndex = 15
Note: instead of ColorIndex number 15 (light gray), you can use any ColorIndex number.
4. Close the two For Next loops.
Next j
Next i
5. Test the program.
Result so far.
Macro VBA Excel Page.13
Handout Macro VBA Excel
For example, for i = 1 and j = 1, Excel VBA colors Cells(1,1), for i = 1 and j = 3 (Step 2), Excel VBA colors
Cells(1,3), for i = 1 and j = 5, Excel VBA colors Cells(1,5), for i = 3 (Step 2) and j = 1, Excel VBA colors Cells(3,1),
etc.
6. We are almost there. The only thing we need to do, is color the cells which are offset by 1 row below and 1
column to the right of the cells already colored. Add the following code line to the loop.
Cells(i, j).Offset(1, 1).Interior.ColorIndex = 15
7. Test the program.
Result:
Macro VBA Excel Page.14
Handout Macro VBA Excel
Sort Numbers
Below we will look at a program in Excel VBA that sorts numbers.
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, we declare three variables of type Integer and one Range object.
Dim i As Integer, j As Integer, temp As Integer, rng As Range
2. We initialize the Range object rng with the numbers in Column A. We use the CurrentRegion property for this.
CurrentRegion is useful when we don't know the exact boundaries of a range in advance (we want this program
to work for 9 numbers but also for 90 numbers).
Set rng = Range("A1").CurrentRegion
3. We start two For Next loops.
For i = 1 To rng.Count
For j = i + 1 To rng.Count
Explanation: rng.Count equals 9, so the first two code lines reduce to For i = 1 to 9 and For j = i + 1 to 9. For i = 1,
j = 2, 3, ... , 8 and 9 are checked.
4. To sort the numbers properly, we compare the first number with the next number. If the next number is smaller,
we swap the numbers. Add the following If Then statement.
If rng.Cells(j) < rng.Cells(i) Then
End If
Macro VBA Excel Page.15
Handout Macro VBA Excel
If the above statement is true, we swap the numbers.
For example: for i = 1 and j = 2, the numbers 2 and 10 are being compared. The above statement is not true.
Thus, no need to swap the numbers. Excel VBA increments j by 1 and repeats the code lines for i = 1 and j = 3.
You can easily see that 5 is larger than 2, so still no need to swap the numbers. We get the same result for j = 4, j
= 5 and j = 6. When we arrive at j = 7, the above statement is true since 1 is smaller than 2.
5. We swap the numbers. We temporarily store one number to temp, so that Excel VBA can swap the numbers
properly. Add the following code lines in the If statement.
'swap numbers
temp = rng.Cells(i)
rng.Cells(i) = rng.Cells(j)
rng.Cells(j) = temp
6. We close the second For Next loop (Outside the If statement).
Next j
For i = 1 and j = 7, Excel VBA swapped the numbers. That means we get 1 at the first position and 2 at position
7. Now that we have 1 at the first position, we will compare this value with 5 (for j = 8) and 4 (for j = 9). There is
no need to swap the numbers (1 is the smallest number). This way Excel VBA gets (for i = 1) the smallest
number at the first position. To get the second smallest number at the second position, Excel VBA repeats the
exact same steps for i = 2. To get the third smallest number at the third position, Excel VBA repeats the exact
same steps for i = 3, etc.
7. Close the first For Next loop (Outside the If statement).
Next i
8. Test your program.
Result:

More Related Content

What's hot

Sample Excel 2013 Advanced Essentials
Sample Excel 2013 Advanced EssentialsSample Excel 2013 Advanced Essentials
Sample Excel 2013 Advanced Essentials
learnbydoing
 
Real World Excel Formulas
Real World Excel FormulasReal World Excel Formulas
Excel formulas-manual
Excel formulas-manualExcel formulas-manual
Excel formulas-manual
srv1972
 
Calc lessons
Calc lessonsCalc lessons
Calc lessons
Apolinar Fudalan
 
Fill series. Data validation. Excel Tutorial
Fill series. Data validation. Excel TutorialFill series. Data validation. Excel Tutorial
Fill series. Data validation. Excel Tutorial
Ilgar Zarbaliyev
 
New Dynamic Array Functions. Excel Tutorial
New Dynamic Array Functions. Excel TutorialNew Dynamic Array Functions. Excel Tutorial
New Dynamic Array Functions. Excel Tutorial
Ilgar Zarbaliyev
 
Excel Data Management
Excel Data ManagementExcel Data Management
Excel Data Management
Rachel Espino
 
AutoCorrect - Excel 2013 Tutorial
AutoCorrect - Excel 2013 TutorialAutoCorrect - Excel 2013 Tutorial
AutoCorrect - Excel 2013 Tutorial
SpreadsheetTrainer
 
Spreadsheet Package
Spreadsheet PackageSpreadsheet Package
Spreadsheet Package
Sanjaya Dharmadasa
 
MS Excel formula tab slides
MS Excel formula tab slidesMS Excel formula tab slides
MS Excel formula tab slides
Muhammad Zaman
 
Rick Watkins Docs
Rick Watkins DocsRick Watkins Docs
Rick Watkins Docs
rickwatkins
 
Advance MS Excel
Advance MS ExcelAdvance MS Excel
Advance MS Excel
acute23
 
Excel Formulas Functions
Excel Formulas FunctionsExcel Formulas Functions
Excel Formulas Functions
simply_coool
 
Excel-VBA
Excel-VBAExcel-VBA
Excel-VBA
DHRUYEN HADIYA
 
De vry math 399 all ilabs latest 2016 november
De vry math 399 all ilabs latest 2016 novemberDe vry math 399 all ilabs latest 2016 november
De vry math 399 all ilabs latest 2016 november
lenasour
 
Row, Column, Index, Match, Offset Functions. Excel Tutorial
Row, Column, Index, Match, Offset Functions. Excel TutorialRow, Column, Index, Match, Offset Functions. Excel Tutorial
Row, Column, Index, Match, Offset Functions. Excel Tutorial
Ilgar Zarbaliyev
 
10 Excel Formulas that will help you in any Job
10 Excel Formulas that will help you in any Job10 Excel Formulas that will help you in any Job
10 Excel Formulas that will help you in any Job
Hitesh Biyani
 
SPL 12.1 | Multi Dimensional(Two) Array Practice Problems
SPL 12.1 | Multi Dimensional(Two) Array Practice ProblemsSPL 12.1 | Multi Dimensional(Two) Array Practice Problems
SPL 12.1 | Multi Dimensional(Two) Array Practice Problems
Mohammad Imam Hossain
 
Excel text functions
Excel text functionsExcel text functions
Excel text functions
Kevin McLogan
 

What's hot (19)

Sample Excel 2013 Advanced Essentials
Sample Excel 2013 Advanced EssentialsSample Excel 2013 Advanced Essentials
Sample Excel 2013 Advanced Essentials
 
Real World Excel Formulas
Real World Excel FormulasReal World Excel Formulas
Real World Excel Formulas
 
Excel formulas-manual
Excel formulas-manualExcel formulas-manual
Excel formulas-manual
 
Calc lessons
Calc lessonsCalc lessons
Calc lessons
 
Fill series. Data validation. Excel Tutorial
Fill series. Data validation. Excel TutorialFill series. Data validation. Excel Tutorial
Fill series. Data validation. Excel Tutorial
 
New Dynamic Array Functions. Excel Tutorial
New Dynamic Array Functions. Excel TutorialNew Dynamic Array Functions. Excel Tutorial
New Dynamic Array Functions. Excel Tutorial
 
Excel Data Management
Excel Data ManagementExcel Data Management
Excel Data Management
 
AutoCorrect - Excel 2013 Tutorial
AutoCorrect - Excel 2013 TutorialAutoCorrect - Excel 2013 Tutorial
AutoCorrect - Excel 2013 Tutorial
 
Spreadsheet Package
Spreadsheet PackageSpreadsheet Package
Spreadsheet Package
 
MS Excel formula tab slides
MS Excel formula tab slidesMS Excel formula tab slides
MS Excel formula tab slides
 
Rick Watkins Docs
Rick Watkins DocsRick Watkins Docs
Rick Watkins Docs
 
Advance MS Excel
Advance MS ExcelAdvance MS Excel
Advance MS Excel
 
Excel Formulas Functions
Excel Formulas FunctionsExcel Formulas Functions
Excel Formulas Functions
 
Excel-VBA
Excel-VBAExcel-VBA
Excel-VBA
 
De vry math 399 all ilabs latest 2016 november
De vry math 399 all ilabs latest 2016 novemberDe vry math 399 all ilabs latest 2016 november
De vry math 399 all ilabs latest 2016 november
 
Row, Column, Index, Match, Offset Functions. Excel Tutorial
Row, Column, Index, Match, Offset Functions. Excel TutorialRow, Column, Index, Match, Offset Functions. Excel Tutorial
Row, Column, Index, Match, Offset Functions. Excel Tutorial
 
10 Excel Formulas that will help you in any Job
10 Excel Formulas that will help you in any Job10 Excel Formulas that will help you in any Job
10 Excel Formulas that will help you in any Job
 
SPL 12.1 | Multi Dimensional(Two) Array Practice Problems
SPL 12.1 | Multi Dimensional(Two) Array Practice ProblemsSPL 12.1 | Multi Dimensional(Two) Array Practice Problems
SPL 12.1 | Multi Dimensional(Two) Array Practice Problems
 
Excel text functions
Excel text functionsExcel text functions
Excel text functions
 

Viewers also liked

NILAI TUGAS / PRAKTIKUM 3 FKIP BIOLOGI UIR
NILAI TUGAS / PRAKTIKUM 3 FKIP BIOLOGI UIR NILAI TUGAS / PRAKTIKUM 3 FKIP BIOLOGI UIR
NILAI TUGAS / PRAKTIKUM 3 FKIP BIOLOGI UIR
eka pandu cynthia
 
In-situ Treatment Cell in Pacaya Samiria National Reserve open
In-situ Treatment Cell in Pacaya Samiria National Reserve openIn-situ Treatment Cell in Pacaya Samiria National Reserve open
In-situ Treatment Cell in Pacaya Samiria National Reserve open
Fernando de Torres Jr.
 
Investor presentation december 2015 v final
Investor presentation december 2015 v finalInvestor presentation december 2015 v final
Investor presentation december 2015 v final
CrestwoodCorporate
 
Libmark october 2015
Libmark october 2015Libmark october 2015
Libmark october 2015
Kylie Carlson
 
CareerFitter
CareerFitterCareerFitter
CareerFitter
Valerie McIntyre
 
Procesontwerp inrichting leer- en werkomgeving Zorgpartners | Thuiszorg
Procesontwerp inrichting leer- en werkomgeving Zorgpartners | ThuiszorgProcesontwerp inrichting leer- en werkomgeving Zorgpartners | Thuiszorg
Procesontwerp inrichting leer- en werkomgeving Zorgpartners | Thuiszorg
Evelien Verkade
 
Hindustan lever vs eureka forbes (aquasure case)
Hindustan lever vs eureka forbes (aquasure case)Hindustan lever vs eureka forbes (aquasure case)
Hindustan lever vs eureka forbes (aquasure case)
Altacit Global
 
20 ma y 2016 ram deep
20 ma y 2016  ram deep20 ma y 2016  ram deep
20 ma y 2016 ram deep
Santosh Tiwari
 
Presentación matemática financiera
Presentación matemática financieraPresentación matemática financiera
Presentación matemática financiera
alfonnavarro
 
LGU Revenue & Resources Mobilisation Tools
LGU Revenue & Resources Mobilisation ToolsLGU Revenue & Resources Mobilisation Tools
LGU Revenue & Resources Mobilisation Tools
rommer101
 
Basic patterns for capability map level 0
Basic patterns for capability map level 0Basic patterns for capability map level 0
Basic patterns for capability map level 0
Jörgen Dahlberg
 
Techniques I like
Techniques I likeTechniques I like
Techniques I like
Danielle
 

Viewers also liked (12)

NILAI TUGAS / PRAKTIKUM 3 FKIP BIOLOGI UIR
NILAI TUGAS / PRAKTIKUM 3 FKIP BIOLOGI UIR NILAI TUGAS / PRAKTIKUM 3 FKIP BIOLOGI UIR
NILAI TUGAS / PRAKTIKUM 3 FKIP BIOLOGI UIR
 
In-situ Treatment Cell in Pacaya Samiria National Reserve open
In-situ Treatment Cell in Pacaya Samiria National Reserve openIn-situ Treatment Cell in Pacaya Samiria National Reserve open
In-situ Treatment Cell in Pacaya Samiria National Reserve open
 
Investor presentation december 2015 v final
Investor presentation december 2015 v finalInvestor presentation december 2015 v final
Investor presentation december 2015 v final
 
Libmark october 2015
Libmark october 2015Libmark october 2015
Libmark october 2015
 
CareerFitter
CareerFitterCareerFitter
CareerFitter
 
Procesontwerp inrichting leer- en werkomgeving Zorgpartners | Thuiszorg
Procesontwerp inrichting leer- en werkomgeving Zorgpartners | ThuiszorgProcesontwerp inrichting leer- en werkomgeving Zorgpartners | Thuiszorg
Procesontwerp inrichting leer- en werkomgeving Zorgpartners | Thuiszorg
 
Hindustan lever vs eureka forbes (aquasure case)
Hindustan lever vs eureka forbes (aquasure case)Hindustan lever vs eureka forbes (aquasure case)
Hindustan lever vs eureka forbes (aquasure case)
 
20 ma y 2016 ram deep
20 ma y 2016  ram deep20 ma y 2016  ram deep
20 ma y 2016 ram deep
 
Presentación matemática financiera
Presentación matemática financieraPresentación matemática financiera
Presentación matemática financiera
 
LGU Revenue & Resources Mobilisation Tools
LGU Revenue & Resources Mobilisation ToolsLGU Revenue & Resources Mobilisation Tools
LGU Revenue & Resources Mobilisation Tools
 
Basic patterns for capability map level 0
Basic patterns for capability map level 0Basic patterns for capability map level 0
Basic patterns for capability map level 0
 
Techniques I like
Techniques I likeTechniques I like
Techniques I like
 

Similar to การบ้านวิชาห้องสมุด

Loop in excel
Loop in excel Loop in excel
Loop in excel
qabas abdal zahraa
 
Macros
MacrosMacros
Introduction to micro soft Training ms Excel.ppt
Introduction to micro soft Training ms Excel.pptIntroduction to micro soft Training ms Excel.ppt
Introduction to micro soft Training ms Excel.ppt
dejene3
 
MS EXCEL.ppt
MS EXCEL.pptMS EXCEL.ppt
MS EXCEL.ppt
DondonGoles
 
Excel Tutorials - Random Value Selection from a List
Excel Tutorials - Random Value Selection from a ListExcel Tutorials - Random Value Selection from a List
Excel Tutorials - Random Value Selection from a List
Merve Nur Taş
 
ENGR 102B Microsoft Excel Proficiency LevelsPlease have your in.docx
ENGR 102B Microsoft Excel Proficiency LevelsPlease have your in.docxENGR 102B Microsoft Excel Proficiency LevelsPlease have your in.docx
ENGR 102B Microsoft Excel Proficiency LevelsPlease have your in.docx
YASHU40
 
Creating Formulas in Excel
Creating Formulas in ExcelCreating Formulas in Excel
Creating Formulas in Excel
Kim Estes
 
Excel training
Excel trainingExcel training
Excel training
Alexandru Gologan
 
Excel 2007- Enter Formulas
Excel 2007- Enter FormulasExcel 2007- Enter Formulas
Excel 2007- Enter Formulas
Oklahoma Dept. Mental Health
 
Excel Function Training
Excel Function TrainingExcel Function Training
Excel Function Training
kapileshwar kumar
 
Ms excel 2016_function
Ms excel 2016_functionMs excel 2016_function
Ms excel 2016_function
Paktia University
 
Excel formulas
Excel formulasExcel formulas
Excel formulas
devangimehta
 
Regression analysis in excel
Regression analysis in excelRegression analysis in excel
Regression analysis in excel
Thilina Rathnayaka
 
Functions and formulas of ms excel
Functions and formulas of ms excelFunctions and formulas of ms excel
Functions and formulas of ms excel
madhuparna bhowmik
 
Microsoft Excel Project 1 Presentation
Microsoft Excel Project 1 PresentationMicrosoft Excel Project 1 Presentation
Microsoft Excel Project 1 Presentation
jmartinvvc
 
Formulas and functions
Formulas and functions Formulas and functions
Formulas and functions
ManishTiwari326
 
2016 Excel/VBA Notes
2016 Excel/VBA Notes2016 Excel/VBA Notes
2016 Excel/VBA Notes
Yang Ye
 
Ms excel 2007 tutorial
Ms excel 2007 tutorialMs excel 2007 tutorial
Ms excel 2007 tutorial
jks2010
 
Excell%20basic%20training(3) 143
Excell%20basic%20training(3) 143Excell%20basic%20training(3) 143
Excell%20basic%20training(3) 143
Ramesh Meti
 
G10 Unit 4.pptx
G10 Unit 4.pptxG10 Unit 4.pptx
G10 Unit 4.pptx
abdulwehab2
 

Similar to การบ้านวิชาห้องสมุด (20)

Loop in excel
Loop in excel Loop in excel
Loop in excel
 
Macros
MacrosMacros
Macros
 
Introduction to micro soft Training ms Excel.ppt
Introduction to micro soft Training ms Excel.pptIntroduction to micro soft Training ms Excel.ppt
Introduction to micro soft Training ms Excel.ppt
 
MS EXCEL.ppt
MS EXCEL.pptMS EXCEL.ppt
MS EXCEL.ppt
 
Excel Tutorials - Random Value Selection from a List
Excel Tutorials - Random Value Selection from a ListExcel Tutorials - Random Value Selection from a List
Excel Tutorials - Random Value Selection from a List
 
ENGR 102B Microsoft Excel Proficiency LevelsPlease have your in.docx
ENGR 102B Microsoft Excel Proficiency LevelsPlease have your in.docxENGR 102B Microsoft Excel Proficiency LevelsPlease have your in.docx
ENGR 102B Microsoft Excel Proficiency LevelsPlease have your in.docx
 
Creating Formulas in Excel
Creating Formulas in ExcelCreating Formulas in Excel
Creating Formulas in Excel
 
Excel training
Excel trainingExcel training
Excel training
 
Excel 2007- Enter Formulas
Excel 2007- Enter FormulasExcel 2007- Enter Formulas
Excel 2007- Enter Formulas
 
Excel Function Training
Excel Function TrainingExcel Function Training
Excel Function Training
 
Ms excel 2016_function
Ms excel 2016_functionMs excel 2016_function
Ms excel 2016_function
 
Excel formulas
Excel formulasExcel formulas
Excel formulas
 
Regression analysis in excel
Regression analysis in excelRegression analysis in excel
Regression analysis in excel
 
Functions and formulas of ms excel
Functions and formulas of ms excelFunctions and formulas of ms excel
Functions and formulas of ms excel
 
Microsoft Excel Project 1 Presentation
Microsoft Excel Project 1 PresentationMicrosoft Excel Project 1 Presentation
Microsoft Excel Project 1 Presentation
 
Formulas and functions
Formulas and functions Formulas and functions
Formulas and functions
 
2016 Excel/VBA Notes
2016 Excel/VBA Notes2016 Excel/VBA Notes
2016 Excel/VBA Notes
 
Ms excel 2007 tutorial
Ms excel 2007 tutorialMs excel 2007 tutorial
Ms excel 2007 tutorial
 
Excell%20basic%20training(3) 143
Excell%20basic%20training(3) 143Excell%20basic%20training(3) 143
Excell%20basic%20training(3) 143
 
G10 Unit 4.pptx
G10 Unit 4.pptxG10 Unit 4.pptx
G10 Unit 4.pptx
 

Recently uploaded

How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17
Celine George
 
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
Nguyen Thanh Tu Collection
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...
Nguyen Thanh Tu Collection
 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
Kalna College
 
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxA Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
OH TEIK BIN
 
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
TechSoup
 
BPSC-105 important questions for june term end exam
BPSC-105 important questions for june term end examBPSC-105 important questions for june term end exam
BPSC-105 important questions for june term end exam
sonukumargpnirsadhan
 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
Kalna College
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
heathfieldcps1
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
deepaannamalai16
 
Educational Technology in the Health Sciences
Educational Technology in the Health SciencesEducational Technology in the Health Sciences
Educational Technology in the Health Sciences
Iris Thiele Isip-Tan
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
nitinpv4ai
 
220711130097 Tulip Samanta Concept of Information and Communication Technology
220711130097 Tulip Samanta Concept of Information and Communication Technology220711130097 Tulip Samanta Concept of Information and Communication Technology
220711130097 Tulip Samanta Concept of Information and Communication Technology
Kalna College
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
deepaannamalai16
 
Oliver Asks for More by Charles Dickens (9)
Oliver Asks for More by Charles Dickens (9)Oliver Asks for More by Charles Dickens (9)
Oliver Asks for More by Charles Dickens (9)
nitinpv4ai
 
How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17
Celine George
 
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
220711130100 udita Chakraborty  Aims and objectives of national policy on inf...220711130100 udita Chakraborty  Aims and objectives of national policy on inf...
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
Kalna College
 
Simple-Present-Tense xxxxxxxxxxxxxxxxxxx
Simple-Present-Tense xxxxxxxxxxxxxxxxxxxSimple-Present-Tense xxxxxxxxxxxxxxxxxxx
Simple-Present-Tense xxxxxxxxxxxxxxxxxxx
RandolphRadicy
 
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
ImMuslim
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
nitinpv4ai
 

Recently uploaded (20)

How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17
 
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...
 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
 
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxA Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
 
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
 
BPSC-105 important questions for june term end exam
BPSC-105 important questions for june term end examBPSC-105 important questions for june term end exam
BPSC-105 important questions for june term end exam
 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
 
Educational Technology in the Health Sciences
Educational Technology in the Health SciencesEducational Technology in the Health Sciences
Educational Technology in the Health Sciences
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
 
220711130097 Tulip Samanta Concept of Information and Communication Technology
220711130097 Tulip Samanta Concept of Information and Communication Technology220711130097 Tulip Samanta Concept of Information and Communication Technology
220711130097 Tulip Samanta Concept of Information and Communication Technology
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
 
Oliver Asks for More by Charles Dickens (9)
Oliver Asks for More by Charles Dickens (9)Oliver Asks for More by Charles Dickens (9)
Oliver Asks for More by Charles Dickens (9)
 
How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17
 
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
220711130100 udita Chakraborty  Aims and objectives of national policy on inf...220711130100 udita Chakraborty  Aims and objectives of national policy on inf...
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
 
Simple-Present-Tense xxxxxxxxxxxxxxxxxxx
Simple-Present-Tense xxxxxxxxxxxxxxxxxxxSimple-Present-Tense xxxxxxxxxxxxxxxxxxx
Simple-Present-Tense xxxxxxxxxxxxxxxxxxx
 
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
 

การบ้านวิชาห้องสมุด

  • 1. Macro VBA Excel Page.1 Handout Macro VBA Excel Loop Looping is one of the most powerful programming techniques. A loop in Excel VBA enables you to loop through a range of cells with just a few codes lines. Single Loop You can use a single loop to loop through a one-dimensional range of cells. Place a command button on your worksheet and add the following code lines: Dim i As Integer For i = 1 To 6 Cells(i, 1).Value = 100 Next i Result when you click the command button on the sheet: Explanation: The code lines between For and Next will be executed six times. For i = 1, Excel VBA enters the value 100 into the cell at the intersection of row 1 and column 1. When Excel VBA reaches Next i, it increases i with 1 and jumps back to the For statement. For i = 2, Excel VBA enters the value 100 into the cell at the intersection of row 2 and column 1, etc. Note: it is good practice to always indent (tab) the code between the words For and Next. This makes your code easier to read. Double Loop You can use a double loop to loop through a two-dimensional range of cells. Place a command button on your worksheet and add the following code lines: Dim i As Integer, j As Integer For i = 1 To 6
  • 2. Macro VBA Excel Page.2 Handout Macro VBA Excel For j = 1 To 2 Cells(i, j).Value = 100 Next j Next i Result when you click the command button on the sheet: Explanation: For i = 1 and j = 1, Excel VBA enters the value 100 into the cell at the intersection of row 1 and column 1. When Excel VBA reaches Next j, it increases j with 1 and jumps back to the For j statement. For i = 1 and j = 2, Excel VBA enters the value 100 into the cell at the intersection of row 1 and column 2. Next, Excel VBA ignores Next j because j only runs from 1 to 2. When Excel VBA reaches Next i, it increases i with 1 and jumps back to the For i statement. For i = 2 and j = 1, Excel VBA enters the value 100 into the cell at the intersection of row 2 and column 1, etc. Triple Loop You can use a triple loop to loop through two-dimensional ranges on multiple Excel worksheets. Place a command button on your worksheet and add the following code lines: Dim c As Integer, i As Integer, j As Integer For c = 1 To 3 For i = 1 To 6 For j = 1 To 2 Worksheets(c).Cells(i, j).Value = 100 Next j Next i Next c Explanation: The only change made compared to the code for the double loop is that we have added one more loop and added Worksheets(c). in front of Cells to get the two-dimensional range on the first sheet for c = 1, the second sheet for c = 2 and the third sheet for c = 3. Download the Excel file to see this result. Do While Loop Besides the For Next loop, there are other loops in Excel VBA. For example, the Do While Loop. Code placed between Do While and Loop will be repeated as long as the part after Do While is true.
  • 3. Macro VBA Excel Page.3 Handout Macro VBA Excel 1. Place a command button on your worksheet and add the following code lines: Dim i As Integer i = 1 Do While i < 6 Cells(i, 1).Value = 20 i = i + 1 Loop Result when you click the command button on the sheet: Explanation: as long as i is lower than 6, Excel VBA enters the value 20 into the cell at the intersection of row i and column 1 and increments i by 1. In Excel VBA (and in other programming languages), the symbol '=' means becomes. It does not mean equal. So i = i + 1 means i becomes i + 1. In other words: take the present value of i and add 1 to it. For example, if i = 1, i becomes 1 + 1 = 2. As a result, the value 20 will be placed into column A five times (not six because Excel VBA stops when i equals 6). 2. Enter some numbers in column A. 3. Place a command button on your worksheet and add the following code lines: Dim i As Integer i = 1 Do While Cells(i, 1).Value <> "" Cells(i, 2).Value = Cells(i, 1).Value + 10
  • 4. Macro VBA Excel Page.4 Handout Macro VBA Excel i = i + 1 Loop Result when you click the command button on the sheet: Explanation: as long as Cells(i, 1).Value is not empty (<> means not equal to), Excel VBA enters the value into the cell at the intersection of row i and column 2, that is 10 higher than the value in the cell at the intersection of row i and column 1. Excel VBA stops when i equals 7 because Cells(7, 1).Value is empty. This is a great way to loop through any number of rows on a worksheet.
  • 5. Macro VBA Excel Page.5 Handout Macro VBA Excel Loop through Defined Range Below we will look at a program that loops through a defined range. For example, when we want to square the numbers in Range("A1:A3"). Did you know you can also loop through a dynamic range? Situation: Place a command button on your worksheet and add the following code lines: 1. First, we declare two Range objects. We call the Range objects rng and cell. Dim rng As Range, cell As Range 2. We initialize the Range object rng with Range("A1:A3"). Set rng = Range("A1:A3") 3. Add the For Each Next loop. For Each cell In rng Next cell Note: rng and cell are randomly chosen here, you can use any names. Remember to refer to these names in the rest of your code. 4. Next, we square each cell in this range. To achieve this, add the following code line to the loop: cell.Value = cell.Value * cell.Value Result when you click the command button on the sheet:
  • 6. Macro VBA Excel Page.6 Handout Macro VBA Excel 5. If you want to check each cell in a randomly selected range, simply replace: Set rng = Range("A1:A3") with: Set rng = Selection 6. Now, for example select Range("A1:A2"). Result when you click the command button on the sheet:
  • 7. Macro VBA Excel Page.7 Handout Macro VBA Excel Loop through Entire Column Below we will look at a program in Excel VBA that loops through the entire first column and colors all values that are lower than a certain value. Place a command button on your worksheet and add the following code lines: 1. First, declare a variable called i of type Long. We use a variable of type Long here because Long variables have larger capacity than Integer variables. Dim i As Long 2. Next, add the code line which changes the font color of all the cells in column A to black. Columns(1).Font.Color = vbBlack 3. Add the loop. For i = 1 To Rows.Count Next i
  • 8. Macro VBA Excel Page.8 Handout Macro VBA Excel Note: worksheets can have up to 65,536 rows in Excel 2003 and up to 1,048,576 rows in Excel 2007 and Excel 2010. No matter what version you are using, the code line above loops through all rows (downloadable Excel file is in Excel 97-2003 format). 4. Next, we color all values that are lower than the value entered into cell D2. Empty cells are ignored. Add the following code lines to the loop. If Cells(i, 1).Value < Range("D2").Value And Not IsEmpty(Cells(i, 1).Value) Then Cells(i, 1).Font.Color = vbRed End If Result when you click the command button on the sheet (this may take a while):
  • 9. Macro VBA Excel Page.9 Handout Macro VBA Excel Do Until Loop Although not used very often on this site, you might find yourself in a situation where you want to use the Do Until Loop in Excel VBA. Code placed between Do Until and Loop will be repeated until the part after Do Until is true. Place a command button on your worksheet and add the following code lines: Dim i As Integer i = 1 Do Until i > 6 Cells(i, 1).Value = 20 i = i + 1 Loop Result when you click the command button on the sheet: Explanation: until i is higher than 6, Excel VBA places the value 20 into the cell at the intersection of row i and column 1 and increments i by 1. As a result, the value 20 will be placed into column A six times (not seven because Excel VBA stops when i equals 7).
  • 10. Macro VBA Excel Page.10 Handout Macro VBA Excel Step Keyword You can use the Step keyword in Excel VBA to specify a different increment for the counter variable of a loop. 1. Place a command button on your worksheet and add the following code lines: Dim i As Integer For i = 1 To 6 Step 2 Cells(i, 1).Value = 100 Next i Result when you click the command button on the sheet: Explanation: The code lines between For and Next will be executed three times. For i = 1, Excel VBA enters the value 100 into the cell at the intersection of row 1 and column 1. When Excel VBA reaches Next i, it increases i with 2 and jumps back to the For statement. For i = 3, Excel VBA enters the value 100 into the cell at the intersection of row 3 and column 1, etc. 2. Place a command button on your worksheet and add the following code lines: Dim j As Integer For j = 8 To 3 Step -1 Cells(6, j).Value = 50 Next j Result when you click the command button on the sheet:
  • 11. Macro VBA Excel Page.11 Handout Macro VBA Excel Explanation: The code lines between For and Next will be executed six times. For j = 8, Excel VBA enters the value 50 into the cell at the intersection of row 6 and column 8. When Excel VBA reaches Next j, it decreases j with 1 and jumps back to the For statement. For j = 7, Excel VBA enters the value 50 into the cell at the intersection of row 6 and column 7, etc.
  • 12. Macro VBA Excel Page.12 Handout Macro VBA Excel Create a Pattern Below we will look at a program in Excel VBA that creates a pattern. Situation: Place a command button on your worksheet and add the following code lines: 1. First, we declare two variables of type Integer. One named i and one named j. Dim i As Integer, j As Integer 2. Second, we add two For Next loops. For i = 1 To 5 Step 2 For j = 1 To 5 Step 2 3. Next, we add the line which changes the background color of the cells to light gray. Cells(i, j).Interior.ColorIndex = 15 Note: instead of ColorIndex number 15 (light gray), you can use any ColorIndex number. 4. Close the two For Next loops. Next j Next i 5. Test the program. Result so far.
  • 13. Macro VBA Excel Page.13 Handout Macro VBA Excel For example, for i = 1 and j = 1, Excel VBA colors Cells(1,1), for i = 1 and j = 3 (Step 2), Excel VBA colors Cells(1,3), for i = 1 and j = 5, Excel VBA colors Cells(1,5), for i = 3 (Step 2) and j = 1, Excel VBA colors Cells(3,1), etc. 6. We are almost there. The only thing we need to do, is color the cells which are offset by 1 row below and 1 column to the right of the cells already colored. Add the following code line to the loop. Cells(i, j).Offset(1, 1).Interior.ColorIndex = 15 7. Test the program. Result:
  • 14. Macro VBA Excel Page.14 Handout Macro VBA Excel Sort Numbers Below we will look at a program in Excel VBA that sorts numbers. Situation: Place a command button on your worksheet and add the following code lines: 1. First, we declare three variables of type Integer and one Range object. Dim i As Integer, j As Integer, temp As Integer, rng As Range 2. We initialize the Range object rng with the numbers in Column A. We use the CurrentRegion property for this. CurrentRegion is useful when we don't know the exact boundaries of a range in advance (we want this program to work for 9 numbers but also for 90 numbers). Set rng = Range("A1").CurrentRegion 3. We start two For Next loops. For i = 1 To rng.Count For j = i + 1 To rng.Count Explanation: rng.Count equals 9, so the first two code lines reduce to For i = 1 to 9 and For j = i + 1 to 9. For i = 1, j = 2, 3, ... , 8 and 9 are checked. 4. To sort the numbers properly, we compare the first number with the next number. If the next number is smaller, we swap the numbers. Add the following If Then statement. If rng.Cells(j) < rng.Cells(i) Then End If
  • 15. Macro VBA Excel Page.15 Handout Macro VBA Excel If the above statement is true, we swap the numbers. For example: for i = 1 and j = 2, the numbers 2 and 10 are being compared. The above statement is not true. Thus, no need to swap the numbers. Excel VBA increments j by 1 and repeats the code lines for i = 1 and j = 3. You can easily see that 5 is larger than 2, so still no need to swap the numbers. We get the same result for j = 4, j = 5 and j = 6. When we arrive at j = 7, the above statement is true since 1 is smaller than 2. 5. We swap the numbers. We temporarily store one number to temp, so that Excel VBA can swap the numbers properly. Add the following code lines in the If statement. 'swap numbers temp = rng.Cells(i) rng.Cells(i) = rng.Cells(j) rng.Cells(j) = temp 6. We close the second For Next loop (Outside the If statement). Next j For i = 1 and j = 7, Excel VBA swapped the numbers. That means we get 1 at the first position and 2 at position 7. Now that we have 1 at the first position, we will compare this value with 5 (for j = 8) and 4 (for j = 9). There is no need to swap the numbers (1 is the smallest number). This way Excel VBA gets (for i = 1) the smallest number at the first position. To get the second smallest number at the second position, Excel VBA repeats the exact same steps for i = 2. To get the third smallest number at the third position, Excel VBA repeats the exact same steps for i = 3, etc. 7. Close the first For Next loop (Outside the If statement). Next i 8. Test your program. Result: