SlideShare a Scribd company logo
1 of 15
Download to read offline
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 Essentialslearnbydoing
 
Excel formulas-manual
Excel formulas-manualExcel formulas-manual
Excel formulas-manualsrv1972
 
Fill series. Data validation. Excel Tutorial
Fill series. Data validation. Excel TutorialFill series. Data validation. Excel Tutorial
Fill series. Data validation. Excel TutorialIlgar Zarbaliyev
 
New Dynamic Array Functions. Excel Tutorial
New Dynamic Array Functions. Excel TutorialNew Dynamic Array Functions. Excel Tutorial
New Dynamic Array Functions. Excel TutorialIlgar Zarbaliyev
 
Excel Data Management
Excel Data ManagementExcel Data Management
Excel Data ManagementRachel Espino
 
AutoCorrect - Excel 2013 Tutorial
AutoCorrect - Excel 2013 TutorialAutoCorrect - Excel 2013 Tutorial
AutoCorrect - Excel 2013 TutorialSpreadsheetTrainer
 
MS Excel formula tab slides
MS Excel formula tab slidesMS Excel formula tab slides
MS Excel formula tab slidesMuhammad Zaman
 
Rick Watkins Docs
Rick Watkins DocsRick Watkins Docs
Rick Watkins Docsrickwatkins
 
Advance MS Excel
Advance MS ExcelAdvance MS Excel
Advance MS Excelacute23
 
Excel Formulas Functions
Excel Formulas FunctionsExcel Formulas Functions
Excel Formulas Functionssimply_coool
 
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 novemberlenasour
 
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 TutorialIlgar 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 JobHitesh 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 ProblemsMohammad Imam Hossain
 
Excel text functions
Excel text functionsExcel text functions
Excel text functionsKevin 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 openFernando 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 finalCrestwoodCorporate
 
Libmark october 2015
Libmark october 2015Libmark october 2015
Libmark october 2015Kylie Carlson
 
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 | ThuiszorgEvelien 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
 
Presentación matemática financiera
Presentación matemática financieraPresentación matemática financiera
Presentación matemática financieraalfonnavarro
 
LGU Revenue & Resources Mobilisation Tools
LGU Revenue & Resources Mobilisation ToolsLGU Revenue & Resources Mobilisation Tools
LGU Revenue & Resources Mobilisation Toolsrommer101
 
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 0Jörgen Dahlberg
 
Techniques I like
Techniques I likeTechniques I like
Techniques I likeDanielle
 

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 การบ้านวิชาห้องสมุด

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.pptdejene3
 
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 ListMerve 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.docxYASHU40
 
Creating Formulas in Excel
Creating Formulas in ExcelCreating Formulas in Excel
Creating Formulas in ExcelKim Estes
 
Functions and formulas of ms excel
Functions and formulas of ms excelFunctions and formulas of ms excel
Functions and formulas of ms excelmadhuparna bhowmik
 
Microsoft Excel Project 1 Presentation
Microsoft Excel Project 1 PresentationMicrosoft Excel Project 1 Presentation
Microsoft Excel Project 1 Presentationjmartinvvc
 
2016 Excel/VBA Notes
2016 Excel/VBA Notes2016 Excel/VBA Notes
2016 Excel/VBA NotesYang Ye
 
Ms excel 2007 tutorial
Ms excel 2007 tutorialMs excel 2007 tutorial
Ms excel 2007 tutorialjks2010
 
Excell%20basic%20training(3) 143
Excell%20basic%20training(3) 143Excell%20basic%20training(3) 143
Excell%20basic%20training(3) 143Ramesh Meti
 

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

Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 

Recently uploaded (20)

Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 

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

  • 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: