Macros & VBA Training Series Part 2:
Automate Excel: How to Use Loops to Create a Summary Report
Double-click video to view in Full Screen HD.
Download the file used in this video:
Macros & VBA Training Series
How can we automate this process further?
Please leave a comment below with your answer, and any questions. Thanks!


I’m really enjoying this series, a lot of great tips. I have a monthly task very similar to this, only I receive multiple workbooks (all formatted the same) and have to copy and paste the values from each workbook into individual tabs in a single workbook. Is there a way to automate this process, to have excel retrieve data from closed workbooks (all saved in a single folder) and paste it into a combined workbook, basically creating the workbook you started with in this video?
Thanks Shayne! Yes, this is absolutely possible with VBA. I actually have an entire module dedicated to this topic in my VBA Pro Course. It’s a very similar process where you loop through the workbooks in a list, open each one, copy/paste the data, close the workbook, repeat on the next workbook in the list. Obviously the code is a little more complex, but definitely possible. I will be sharing more about the course soon. Please let me know if you have any questions. Thanks again Shayne!
Hi Jon
Wonderful videos! Macros and VBA learning really became interesting. Thanks
Thanks Anju!
Jon,
These are great videos. I do a lot of very advanced Excel work but very little with macros outside of just recording. You do a excellent job of stepping through and explaining everything.
Thanks A Lot,
Dave
Thank you Dave! I really appreciate the feedback and happy to hear you are learning macros. Have a great weekend! 🙂
Hi, Jon!
I really appreciate the time and effort you’ve put into this video series. I have limited exposure to VBA, but like ‘Andy’ the need for more knowledge is growing. 🙂 I’d love to see how to automate this process further by using VBA to build pivot tables/graphs, dashboards, etc.
Thanks again! Looking forward to the third video!
Jess
Thanks Jess! I’m happy to hear you enjoyed it, and that you are learning VBA. Awesome! Have a good one! 🙂
VBA learning has really become interesting, I like the Pop-Ups that appear now and then.
To help me learn I am coping the Code and writing your comments and my own to be able to understand why I am taking the actions that I am while I write the code. Adding a lot more COMMENTS
Looking forward to Part 3
Sounds great Barry! I’m happy to hear you are learning. Comments are a great way to provide more explanation about your code. They also make it easier to remember what your code does when you look at it in the future. Thanks again!
Really practical. Thanks
Thanks Rosemary!
Thanks a lot….
Man this was a massive step up from video one. what I didn’t understand was the “thisworkbook.activate”. Was “This Workbook” the name of the workbook or was it because the macro was saved within this workbook so when you run the macro it goes to the workbook that the code is saved in. hope this makes sense.
Hi Abdul,
Thanks for the feedback. I know this video is much more advanced than the first, and I appreciate you letting me know.
Great question! The ThisWorkbook property refers to the workbook that the code is stored in. ThisWorkbook.Activate will just activate the workbook that the code is in, so that all the lines of code below it will run on this workbook.
This prevents the code from running on another workbook that you might have open and active. A lot of times when you are debugging and writing code you will hit the run button (F5) or F8 to step through code, and you don’t realize that you have another workbook active. So the code will start running on the wrong workbook. That could cause unexpected changes.
If the active workbook did not contain a sheet name summary, then the code would hit an error on the next line.
So the ThisWorkbook.Activate line just ensures that the code will run on the correct workbook.
There are other ways to go about this referencing, but I wanted to keep it somewhat simple for this example.
Let me know if that makes sense, and if you have any other questions. I’m happy to help. Thanks!
Great detail and comments for a very useful tool. I love all the time taken to explain what’s happening. Am looking forward to video 3.
Thank you Al! I appreciate the nice feedback. 🙂
Awesome job! Just the right level and speed for people that have some good skills and are looking to understand VB a little more.
Looking forward to the next video!
Thanks Laurie! 🙂
Fantastic , This is going to my life easier!!!!!
Woohoo!! Thanks! 🙂
Thanks a lot Jon. I really enjoyed this video. Thanks for your work.
This is awesome ,Thank you so much !!
Thanks Latha!
Jon,
Thanks for the informative video. I found it very advanced. The reason I find it very advanced is due to my lack of knowledge of what code I should reference and when to reference it. For someone like myself that is unfamiliar with code jargon, what advice would you suggest?
Hi Antonio,
Great question! I put together my VBA Pro Course to help you learn the “code jargon” in an easy step-by-step manner. I also recommend the Power Programming books by John Walkenbach if you want really detailed reference material. I hope that helps. Thanks again!
These first two videos are very well done, and a nice introduction to macros. I liked your use of the macro recorder to get the hyperlink code.
Thanks Bill!
Great Videro Jon
I have a question with my code:
Sub rating() Dim i As Integer For i = 2 To 11 If Cells(i, 3).Value > 80 Then Cells(i, 4).Value = "A" ElseIf Cells(i, 3).Value > 65 And Cells(i, 3).Value 50 And Cells(i, 3).Value < 65 Then Cells(i, 4).Value = "C" Else: Cells(i, 4).Value = "Fail" End If Next i End SubFor the code above, i got "End if without block if " error.
Can you have a look on that.
Im using Excel on Mac.
Hi Albert,
I believe the code after the first Then needs to be on a new line. Something like the following.
Sub rating2() Dim i As Integer For i = 2 To 11 If Cells(i, 3).Value > 80 Then Cells(i, 4).Value = "A" ElseIf Cells(i, 3).Value > 65 And Cells(i, 3).Value < 50 And Cells(i, 3).Value < 65 Then Cells(i, 4).Value = "C" Else Cells(i, 4).Value = "Fail" End If Next i End SubIt's best to put the statement after Then on a new line when you have nested ifs like this.
The operator was missing from Cells(i, 3).Value 50 so I added <. You might need to change that. I hope that helps. Let me know if it works for you now. Thanks!
Thx Jon,
That really helps. I find if i write the code like below, excel can run the code with out End If. So in what situation do we need End if? And comparing the code below(like using IF statement many times) and the If…elseif…statement, which one is efficient or faster. Thanks!
Sub rating()
Dim i As Integer
For i = 2 To 11
If Cells(i, 3).Value > 80 Then Cells(i, 4).Value = “A”
If Cells(i, 3).Value > 65 And Cells(i, 3).Value50 And Cells(i, 3).Value < 65 Then Cells(i, 4).Value = "C"
IF Cells(i, 3).Value<50 Then Cells(i, 4).Value = "Fail"
Next i
End Sub
Hi Albert,
The If…Else statement is probably going to be a little more efficient. Once the condition is met, the code will jump to the End If line. It will not evaluate all the other Else statements.
With the If Then lines you listed above, each of those lines will have to be evaluated.
You can also use a Select…Case statement as an alternative to If…Else. I don’t have a public video on that, but here is the help article. https://msdn.microsoft.com/en-us/library/cy37t14y.aspx?f=255&MSPPError=-2147217396
I hope that helps.
Outstanding… I have a book “VB for dummies” I learned more from you in this video than the whole first chapter. You take the time to explain everything very clearly. You should write a book! Thank you Jon
Hi Jon,
Thanks for the wonderful videos, so much helpful for me as a newbie continue doing this for us please and I appreciated it most.
Regards,
Anthony
Thanks Andy! I appreciate the great feedback. Have a good one! 🙂
Dear all
I have one sub test, but it alert me that: end if without block if
Please help me correct this sub
many thanks
Sub test_delete_row()
Dim icountrow As Long
Dim irow As Long
icountrow = Row.Count
For irow = 1 To 10
If Range(“a5”).Offset(icountrow, 0).Value = “” Then Range(“a5”).Offset(icountrow, 0).EntireRow.Delete Shift:=xlUp
End If
Next irow
End Sub
Hi Luis
The code after “Then” needs to be on a new line. You could also leave it as is and delete the End If line. The If statement can be on one line if there is only one line of code after the Then.
The Row.Count will also need to be changed to Rows.Count.
I hope that helps. Let me know if you have questions.
Thanks!
Great video! I can see now, that learning this new skill will definitely make my life easier in the future. I purchased the Excel VBA Programming for dummies as you suggested. I am actually looking forward to learning more about this instead of the dread I was feeling 🙂
Thank you!
Enjoyed the video and following along with the downloaded file for practicing the steps you explained. Looking forward to seeing the next video. You’re explanations of the steps are very clear to understand.
WoW, This is so useful and so easy to follow. I am definitely going to use this at work. Where do I go if I want to see more of your videos or do you only have this series?
Hi Maggie,
Thanks for the great feedback. I do have a full course on VBA called the VBA Pro Course. It is a step-by-step training course on how to learn macros and VBA to automate tasks and create applications. I will be sending you more info on the enrollment for the course. Thanks again!
Hi Jon,
I really would like to thank you for your videos, these are really very helpful. I have messed in a problem and would like to ask for your help. That is:
I have a long list of items’ name in column A having different colors background where items are repeating and number of those items in column B with default background. I have to calculated sum of those numbers for different item on the basis of background color of items’ name. Problem looks like as:
Column A Column B
Pen in Red color Background 400
Pencil in Green BG 500
Book in Ren BG 300
Eraser in Green BG 200
Here, I have to calculate the sum of column B on the basis of color of column A.
I hope to for VBA code from you in this regard.
Hi Rajesh,
Great question. You can use the macro recorder to get the RGB color codes for those background colors. You could also use a custom function. Here is an article that explains it in detail. I hope that helps.
Thanks!
Taking a stab at this, based on the latest video:
Sub ColorCount()
‘Finds the last non-blank cell in a single row or column
‘ Used this page: https://www.excelcampus.com/vba/find-last-row-column-cell/#endcode
Public lRow As Long
Public lCol As Long
‘Find the last non-blank cell in column A(1)
lRow = Cells(Rows.Count, 1).End(xlUp).Row
‘Find the last non-blank cell in row 1
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
Dim RedTotal As Long ‘ Sum of all red cell backgrounds
Dim GreenTotal As Long ‘ Sum of all green cell backgrounds
Dim BlueTotal As Long ‘ Sum of all blue cell backgrounds
ThisWorkbook.Activate
Worksheets(“Sheet1”).Select ‘ Set to correct tab name, just using default
‘ This starts at row 2 (assumes row 1 is headers)
For lSht = 1 To lRow ‘ from second row to last row in sheet
‘ Tests if first row cell background is red color, if so adds to total
If Range(“A1”).Offset(lSht, 0).Interior.Color = RGB(255, 0, 0) Then _
RedTotal = RedTotal + Range(“A1”).Offset(lSht, 1).Value
‘ Tests if first row cell background is green color, if so adds to total
If Range(“A1”).Offset(lSht, 0).Interior.Color = RGB(0, 255, 0) Then _
GreenTotal = GreenTotal + Range(“A1”).Offset(lSht, 1).Value
‘ Tests if first row cell background is blue color, if so adds to total
If Range(“A1”).Offset(lSht, 0).Interior.Color = RGB(0, 0, 255) Then _
BlueTotal = BlueTotal + Range(“A1”).Offset(lSht, 1).Value
Next lRow
‘ Output to message box
MsgBox “Red Total: ” & RedTotal & ” Green Total: ” & GreenTotal & ” Blue Total: ” & BlueTotal
End Sub
Oops, found a couple errors.
Here’s the code I got to work, outputting to different cells:
Sub ColorCount()
‘Finds the last non-blank cell in a single row or column
‘ Used this page: https://www.excelcampus.com/vba/find-last-row-column-cell/#endcode
Dim lRow As Long
Dim lCol As Long
‘Find the last non-blank cell in column A(1)
lRow = Cells(Rows.Count, 1).End(xlUp).Row
‘Find the last non-blank cell in row 1
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
Dim RedTotal As Long ‘ Sum of all red cell backgrounds
Dim GreenTotal As Long ‘ Sum of all green cell backgrounds
Dim BlueTotal As Long ‘ Sum of all blue cell backgrounds
Dim lSht As Long
ThisWorkbook.Activate
Worksheets(“Sheet1”).Select ‘ Set to correct tab name, just using default
‘ This starts at row 2 (assumes row 1 is headers)
For lSht = 1 To lRow
‘ Tests if first row cell background is red color, if so adds to total
If Range(“A1”).Offset(lSht, 0).Interior.Color = RGB(255, 0, 0) Then _
RedTotal = RedTotal + Range(“A1”).Offset(lSht, 1).Value
‘ Tests if first row cell background is green color, if so adds to total
If Range(“A1”).Offset(lSht, 0).Interior.Color = RGB(0, 255, 0) Then _
GreenTotal = GreenTotal + Range(“A1”).Offset(lSht, 1).Value
‘ Tests if first row cell background is blue color, if so adds to total
If Range(“A1”).Offset(lSht, 0).Interior.Color = RGB(0, 0, 255) Then _
BlueTotal = BlueTotal + Range(“A1”).Offset(lSht, 1).Value
Next lSht
Range(“D2”).Value = RedTotal
Range(“D3”).Value = GreenTotal
Range(“D4”).Value = BlueTotal
End Sub
Another great Video. Thank You
Thank you Carlton! 🙂
really good lesson. while watching, I was hoping you would also address the movement of value to bring back – eg in the first quarter the summary number is located in a different cell than 2qtr and each qtr it moves to the right. using a variable vice D10 would allow it to work for however many columns there are
Great suggestion Rich! Yes, we could use a variable instead of D10. I have another video series on how to find the last used cell, row, or column in a sheet. We could use one of these methods to determine the last used cell, set it to a variable, and reference that variable in the formula. I hope that helps. Thanks again!
Very practical day to day tasks that you are showing – really helpful!
Thanks Daryl! I really appreciate the nice feedback. 🙂
Thanks for your video Jon! Is this macro something that could be recorded in a personal macro workbook or would that be unwise? I assume I’d have to change the “activate” code in some manner. I work in an area where I build new models from scratch and need to do a table of contents like this approximately monthly – but always in a totally new workbook with tabs that vary each time. It’d be helpful to have this in my personal macros and not have to go back and find my previous model to recopy the code.
Hi Cassandra,
Great question! Yes, this could absolutely be put in your Personal Macro Workbook. You can run the macro on any open workbook by removing the following line: ThisWorkbook.Activate
Without that line, the macro will run on the active workbook you have open.
I actually have a similar macro in my personal macro wb to list all the sheets in the workbook. I use it all the time.
My Tab Hound also has a Table of Contents feature that make it easy to add a TOC to any workbook. The add-in has more advanced features for creating the TOC, but this macro is the basics of how it works.
I also have a video series on the Personal Macro Workbook that you might like.
Thanks again Cassandra! 🙂
Short and sweet. Best tutorial beginning I have come across.
This is great, and actually something I’ve been looking for to consolidate information from sheets that I enter information into, then have to copy and paste to another workbook.
Two things that I’m really confused about are:
1) How to pass and deal with variables between macros
2) Error handling when something glitches
For example, I process daily manufacturing data and create sheets/forms for the top 5 variances via macros with data to look at why they happened. I use the part number as the name of the tab. When the same part number occurs for two different variances, the excel macro stops because it doesn’t like two tabs with the same name.
Hi Dave,
Great questions! I actually cover these two topics in detail in my VBA Pro Course. Error handling is a very important subject that can save us a lot of time when writing and debugging macros. I typically use a function I wrote to determine if the sheet exists, before trying to create and rename a sheet. A lot will depend on what the macro is doing. You might want it to stop and prompt the user for a new name. Or you might want it to automatically create a new name, append a number, etc. VBA can be used for all these cases.
Passing variables is another important concept that can make our code more efficient. The basics are that you can put the variable name in parenthesis after the macro name. Here is a really simple example.
Sub Macro1() Dim lNum As Long lNum = 5 Call Macro2(lNum) End Sub Sub Macro2(lRow As Long) Rows(lRow).Select End SubMacro1 calls Macro2 and passes the variable through. Notice that the variables don’t have to have the same name, but they should be the same data type.
I hope that helps get you started. Thanks!
So the “lRow As Long” in the parenthesis is the dim statement so you don’t need “dim lRow As Long” after the quotes?
Good to know. Hopefully I can finally get approval for the Pro course!
Jon,
Thank you for these videos. Macros were totally foreign to me but I can already see how much I need to use them. I’m excited to get started….just wish I had more time to work on this! I would be interested in your other courses too.
Hi Jon – Many thanks for that. I found it very helpful and encouraging to see how to produce a sheet with a summary of data from other sheets.
Something that I think I would also find helpful is taking data from a sheet with a lot of data, and creating new sheets with a summary of each selection of data e.g. for different departments which are ‘mixed up’ within the original data sheet. Of course, that may be a bridge too far for a beginner LOL – but if it is do-able, it would save me manually transferring data to a different workbook to summarise and re-arrange the data!
Omg! I’ve found my role model! Amazing!
You rock! Thanks for sharing these how-to videos.
Thank you Judy! 🙂
I’ve tried modifying this code to a report I have to create each day and it’s helped a lot!
One thing I’m stuck on is how to merge text from multiple cells into one. Do you just use the “&” symbol between them like this?
Range(“A3”).Offset(lSht, 9).Formula = “='” & Worksheets(lSht).Name & “‘!C32” & Worksheets(lSht).Name & “‘!C34” & Worksheets(lSht).Name & “‘!C36”
Or is there some trick to merging the text from the cells?
I think I figured out how to merge cells while using the For-Next loop. To explain the code, it’s for a failure analysis report and first I test to see which areas have entries so I create “tags” for those areas that have text. Then I merge the text of cell C32, C34, C36, C38 & C40 and the tags of any cells that have text.
”
I haven’t cleaned up the “‘ End If”‘s. That was one error I had to fix. I thought you needed “End If” if you had an “If”, but apparently for If-Then statements you don’t. Trial by error sometimes…
‘ Problem
‘ Test to see if comments in cell, if so add cause
If Not IsEmpty(Worksheets(lSht).Range(“C32″).Value) Then _
OpsToolingTag = ” (Tooling) ”
‘End If
If Not IsEmpty(Worksheets(lSht).Range(“C34″).Value) Then _
OpsFixturesTag = ” (Fixtures) ”
‘End If
If Not IsEmpty(Worksheets(lSht).Range(“C36″).Value) Then _
OpsLaborTag = ” (Labor) ”
‘End If
If Not IsEmpty(Worksheets(lSht).Range(“C38″).Value) Then _
OpsProgTag = ” (Program) ”
‘End If
If Not IsEmpty(Worksheets(lSht).Range(“C40″).Value) Then _
OpsOtherTag = ” (Other) ”
‘End If
‘ Merge cells for gathering root causes of variation
Range(“A3”).Offset(lSht, 10).Formula = _
Worksheets(lSht).Range(“C32”).Value & _
OpsToolingTag & _
Worksheets(lSht).Range(“C34”).Value & _
OpsFixturesTag & _
Worksheets(lSht).Range(“C36”).Value & _
OpsLaborTag & _
Worksheets(lSht).Range(“C38”).Value & _
OpsProgTag & _
Worksheets(lSht).Range(“C40”).Value & _
OpsOtherTag
Hi Dave,
Yes, that is the correct way to concatenate values or strings together. In VBA we can use the ampersand symbol, just like in Excel formulas.
I have an article on a macro to concatenate multiple cells or ranges that uses a similar approach. You might want to checkout that code.
The other option is to use the Join function. The Join function has an array parameter that allows you to reference an array or list (range). The Join function also has a parameter for a delimiter character.
Here is the help article on the Join function.
https://msdn.microsoft.com/en-us/library/office/gg264098(v=office.15).aspx
The help article isn’t the best, but Join can be a very useful function for these types of projects. Let me know if you have any questions. Thanks!
Thanks Jon, that’s a good bit of information. 🙂
Great video Jon.
I learned a lot.
Thanks.
Could you explain in a more detailed way the macro that you used in the video for the hyperlinks?
Please, see below.
“ActiveSheet.Hyperlinks.Add Anchor:=Range(“A3″).Offset(lSht, 0), _
Address:=””, _
SubAddress:=”‘” & Worksheets(lSht).Name & “‘!A3”
Thanks Luiz! I will create another video that explains that code in more detail. It is basically the same as right-clicking a cell and selecting Hyperlink… from the menu. Then choosing the “Place in this document” option on the left, and selecting a worksheet and cell for the hyperlink destination location. This is the SubAddress parameter in the Hyperlinks.Add method. SubAddress is used when referencing a place within the document. Address is used when referencing a hyperlink to a webpage.
I hope that helps get you started. Please let me know if you have any questions. Thanks!
Thanks Jon.
It worked fine.
In the second video, where you explain the line of code containing the formula, (to extract values from each sheet) in the lsheet loop macro, I understand that you need to use double-quotes around the formula, but why, in your example, do you also leave the single quotes within the double quotes?
Hi Kit,
Great question! The single quotes are wrapped around the worksheet name. Whenever a worksheet name contains a space in the name, Excel automatically adds single quotes (apostrophes) around the sheet name. This is a rule within Excel formulas. The same rule applies when using macros to create formulas. The syntax has to be the exact same so Excel can read the formula.
If the sheet name does not contain a space, then you do not need the single quotes. However, if you are not sure if the sheet name is going to contain a space, then you can add the single quotes to all formulas. If the sheet name does NOT contain a space then Excel will automatically remove the single quotes.
I hope that helps. Please let me know if you have any questions. Thanks!
HI Jon,
I regularly watch your tutorials and they are fun .
Please tell me where I can found The VBA pro tutorials.Can you please share me the link to those videos to my email id “[email protected]”
I am waiting for that.
Hi Arun,
Thanks for the nice feedback. I will be sending you more info on the VBA Pro Course in just a few days. So be on the lookout for an email from me. Thanks again!
Hi Jon,
Is there a way I can delete all other worksheet other than the current worksheet? I have a workbook contains more then 50 worksheets and need to keep each individual one as separate report.
Thank you.
Maple
Hi Maple,
Great question! Here is some code that should work.
Dim ws As Worksheet For Each ws In ActiveWorkbook.Worksheets If ws.Name <> "Sheet to Keep" Then ws.Delete End If Next wsJust replace the word Sheet to Keep with the name of the sheet you want to keep. I hope that helps. Thanks!
Jon,
I downloaded the workbook and was able to see the Modules folder. I cannot, however, see the Module folder in any of my my other
macro-enabled workbooks. Is there a setting which needs to be changed?
Thanks, Joan
Hi Joan,
The modules folder will not appear until you add a code module to the workbook. You can do that from the Insert menu in the VB Editor. Once you add a code module, the Modules folder will automatically appear. I hope that helps.
Thanks for your help and for the tutorials.
Hi Jon,
Great stuff really like this video. I was just thinking in the variation of the code as in this i from the data that looks like a pivot from where the values are reported withing the summary sheet against each name, what if i have to fetch multiple values from the pivot table having different rows like a total value in active, inactive and then a total and report it in a main sheet how the code will look like then?
Great question Raza! The cells and ranges in the pivot tables can be referenced in VBA. Checkout this article by my friend Jon Peltier that shows the VBA code for each range in a pivot table.
Hi Jon,
Please do send in more videos a step by step guide which can help in learning VBA effectively, tutorials like that may prove a great start for tailoring the codes to ones requirements.
Looking forward for your comments and really a superb job that you are doing…
Thank you very much for your great videos! I just want to watch the VBA pro-course videos to understand better the structure of codes. Could you please send them or inform me where to find? Thanks again!
Best Regards,
Hi Merve,
Thanks for the nice comment. I will be sending you more info on the VBA Pro Course in just a few days. So be on the lookout for an email from me. Thanks again! 🙂
Great video, learn a lot more can’t wait till the next video
Awesome! Happy to hear you learned something new. Thanks Jason! 🙂
Hi Jon!
Thanks for your videos. I know that I could do amazing things if I new VBA and your videos are a splendid introduction.
In this last video the goal was to make a summary report with one click of a button. I would like to have the hyperlinks pointing back to the Summary from each Worksheet to be coded in the macro. Otherwise you will not be able to do the report in on click and it is easy to forget that step if you are in a hurry to submit your report. I will try to do that myself as an excercise.
Thanks Martin! You are right that you can do amazing things with VBA. 🙂
Sounds like a great challenge. My Tab Hound add-in also has this feature in the Table of Contents tool, that creates a hyperlink back to the summary or table of contents sheet.
Please feel free to post your code here if you figure it out. Or let me know if you have any questions. Thanks again!
Hi Jon,
Thank you for your videos. I know that I should be able to do amazing things with Ecxel if I knew how to write code. Your videos are a very good introduction.
I gave myself the task to automate the hyperlink from each sheet back to the Summary sheet.
This is what I came up with. It seem to work too 🙂
The last part i just to tidy up the Summary page which gets a couple of extra hyperlinks otherwise.
Sub List_Sheets()
‘List all sheets in the workbook
Dim lCount As Long ‘Long is short for Long interger
Dim lSht As Long ‘Long holds a number
lCount = Worksheets.Count
For lSht = 1 To lCount
Worksheets(1).Range(“A3”).Offset(lSht).Value = Worksheets(lSht).Name
Worksheets(1).Range(“A3”).Offset(lSht, 1).Formula = “='” & Worksheets(lSht).Name & “‘!D10”
‘Underscore character allows us to continue code on a new line
Worksheets(1).Select
ActiveSheet.Hyperlinks.Add Anchor:=Range(“A3″).Offset(lSht, 0), _
Address:=””, _
SubAddress:=”‘” & Worksheets(lSht).Name & “‘!A3”
‘Add Summary hyperlink to every employee sheet
Worksheets(lSht).Select
Range(“A3″).Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=””, SubAddress:= _
“‘” & Worksheets(1).Name & “‘!A3″, TextToDisplay:=”Summary”
Next lSht
Worksheets(1).Select
Range(“A3:B4”).Select
Selection.ClearContents
Selection.ClearFormats
Range(“A4”).Value = Worksheets(1).Name
Hi Martin,
Thanks for posting the code. I just saw this after I posted my last comment, so please ignore that. You beat me to it. 🙂
The code looks good! When writing macros, there are always multiple ways to solve a problem. As you learn more about VBA, you will learn different ways to accomplish a task. I think that’s what makes it fun, and challenging.
Here are a few suggestions for further simplifying the code:
1. We don’t always need to select the object (sheet or range) before modifying it. In the section where you add the Summary hyperlink, we can actually reduce that from 3 lines of code to one line of code.
Before:
Worksheets(lSht).Select Range("A3").Select ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _ "'" & Worksheets(1).Name & "'!A3", TextToDisplay:="Summary"After:
Worksheets(lSht).Hyperlinks.Add Anchor:=Worksheets(lSht).Range("A3"), Address:="", SubAddress:= _ "'" & Worksheets(1).Name & "'!A3", TextToDisplay:="Summary"We can also use an If statement to skip the code for the first sheet. The following If statement checks if lSht is greater than 1. If so, it runs the line of code for the summary hyperlink. If lSht = 1 then it will skip that line of code.
If lSht > 1 Then Worksheets(lSht).ActiveSheet.Hyperlinks.Add Anchor:=Worksheets(lSht).Range("A3"), Address:="", SubAddress:= _ "'" & Worksheets(1).Name & "'!A3", TextToDisplay:="Summary" End IfIf statements are an extremely useful tool in VBA, and any programming language for that matter. They allow us to make decisions with our code based on user actions or conditions of the workbook, worksheet, etc.
I hope that helps. Let me know if you have any questions. Thanks!
In this workbook, how would you add a subtotal row, if the total number of sheets changes from week to week?
Hi Tomais,
Great question! You would first need to find the last used row in the range. In this case, we know what that row number is because we set the lCount variable to the count of the worksheets. We could use lCount + 1 to offset 1 row below the last used row.
In other cases you might not know what the last used row is. I have a 3-part video series on how to find the last used cell, row, or column with VBA. This explains additional techniques for this very common problem. I hope that helps. 🙂
Good day Jon, Thanks for your informative videos i really learnt a lot how ever i am still struggling to create a financial calculator button here is my code as follows:
If Loan.Value=True then calculate
Else “Please insert loan amount”
End if
If rate.Value=True then calculate
Else “Please insert interest rate”
End if
If nper.Value = True then calculate
Else “Please insert number of payments”
End if
loan = Range(“F3”).Value
rate = Range(“F4”).Value
nper = Range(“F5”).Value
If Range(“F6”).Value = True Then
rate = rate / 12
nper = nper * 12
End If
Range(“K3”).Value = -1 * Worksheet.Pmt(rate, nper, loan)
End Sub
Thank you
Video 2 was really helpful to me. I’ve tried something to do that but hyperlinks part was not working in my macro. I’ll try again with ref of video 2.
Looking for more in excel VBA
Thanks.
Hi Jon,
It was a good presentation, interesting. I hadn’t used “hyperlinks” at all in my workbooks so that was a good feature for me. It also emphasises the important role that the Macro Recorder can play.
Thanks
Dave
Thank you Dave! The macro recorder is a fantastic tool for learning the object model and getting snippets of code. Sometimes it’s fun to turn it on when you are doing common tasks in Excel, just to see what code it produces. The code won’t always be the most efficient or use the best techniques. For example, the macro recorder will not create loops, if statements, or variables. But it’s great to learn an object reference and it’s properties and methods.
Thanks again!
Jon
I want to automatically insert new row whenever i enter data in the first column last row of the table i work with in my workbook
just like Access tables do.
Can any body give me some vba code to do so.???
Hi Junaid,
You can use the Worksheet_Change event for this. I just published a video on the change events in Excel. I hope that helps get you started.