Sorting through cluttered folders to find, copy, or relocate specific files is one of the most tedious parts of digital admin work. Whether you are archiving monthly invoices, organizing project deliverables, or pulling specific file types out of a crowded downloads directory, doing it manually takes time and invites human error.
With a custom Excel VBA macro template, you can turn a ten-minute manual chore into a single click. Designed with a clean, user-friendly interface right inside your spreadsheet, this tool handles bulk file transfers automatically based on the exact rules you define.
How the Excel File Manager Works
You do not need to know how to write VBA code to use the template. The worksheet acts as a simple control panel broken down into five straightforward steps:
Folder to look through: Instead of typing out long, error-prone file paths, click the Select Folder button next to the first input box to browse your computer and choose your source directory.
Folder to move/copy files into: Click the second Select Folder button to pick your destination folder where the matching files should land.
Criteria: Enter your filter term in the criteria box. Depending on your workflow, this can be a partial file name (such as “2026_Invoice” or “Q3_Report”) or a specific file extension (like “.pdf” or “.xlsx”) so the macro knows exactly which files to target and which ones to ignore.
Move or Copy?: Use the yellow selection cell at the bottom left to choose your action. Selecting Move transfers the files to the new folder and cleans out the original directory, while switching it to Copy leaves your original files untouched and creates duplicates in the destination folder.
Run Macro: Once your paths, criteria, and action are set, press the Run Macro button in the center of the sheet to execute the transfer immediately.
Why Use an Excel Template for File Organization?
Building this workflow inside Excel gives you a repeatable, error-free system. Once your folder paths and criteria are typed into the cells, you can save the workbook and reuse the exact same setup every week or month without re-selecting your directories. If you manage recurring reporting cycles, batch data exports, or shared team drives, this lightweight template keeps your folders organized so you can focus on actual analysis rather than file housekeeping.
Do you want to create a spinning wheel like in the video below?
In this post, I’ll show you how you can do this, with the help of visual basic. There are a couple of ways you can create a spinning wheel effect. I’ll go over both approaches, and share the code with you so that you can set it up in your own spreadsheet.
Create a spinning wheel effect by rotating an object
The easiest way to spin a wheel, or any object for that matter, is to rotate it. This can be done in visual basic. Before you get started, however, you need to know the name of the shape that you want to spin.
In the above screenshot, I have inserted a wheel into my spreadsheet, but you can use any image. In the top-left-hand corner, you’ll notice it says wheel1 — this is the name of the object. You change this to whatever you want. However, this is what you’ll need to reference in the macro when applying the spin effect.
Now, go into visual basic. This can be done using ALT+F11 shortcut. Then, you’ll need to go to the Insert option from the menu and click on Module.
Then in Module 1, copy the following code in:
Sub SpinEffect()
Dim i As Long
Dim wheel As Shape
Set wheel = ActiveSheet.Shapes("wheel1")
For i = 1 To 100 Step 1
wheel.IncrementRotation 5
DoEvents
Next i
For i = 1 To 100 Step 1
wheel.IncrementRotation 3
DoEvents
Next i
For i = 1 To 100 Step 1
wheel.IncrementRotation 2
DoEvents
Next i
For i = 1 To 500 Step 1
wheel.IncrementRotation 1
DoEvents
Next i
End Sub
At the beginning of the code, I specify the name of my object — wheel1. This is where you need to update the code to reflect the name of your object.
The rest of the code is going through a series of loops. The first one is rotating the image by 5 degrees, then 3 degrees, then 2, and finally 1. The last loop goes through 500 steps and is the longest. You can adjust these to change the speed of the wheel’s rotation.
You can also insert a shape that links to this macro, so that it effectively becomes a button. In my example, I created a rectangle and added the text ‘SPIN’ onto it. If you go to the Insert menu on the Excel ribbon and select Shapes, you can create your own.
Once you’ve created a shape, you can assign a macro to it by right-clicking on the shape and selecting Assign Macro.
Then, select your macro and click on OK.
Now, anytime you click on the button, the macro will run, and your object will spin.
The one limitation about this method is that there is no way to know which value your wheel landed on. It spins, but there is no easy way to determine what it landed on. This is where the second method comes into play.
Creating a spin effect by changing visibility
This method is a bit more complex, but it addresses the main issues from the first approach, which is that you’ll known which value was selected.
I’m going to use the same wheel, but this time I’m going to make nine copies of it — one for each possible outcome. I will do the rotations myself and then just toggle the visibility using code. The setup can be a bit more tedious here because you’ll need to make sure the objects are on top of one another and that the rotations are precisely in the right position.
You’ll have to do this for each rotation and each object. You’ll also want to name each individual object so that you know which value it corresponds to.
Once the objects are all aligned, then you can insert the following code:
#If VBA7 Then
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If
Sub spin()
Dim wheel1 As Shape
Dim wheel2 As Shape
Dim wheel3 As Shape
Dim wheel4 As Shape
Dim wheel5 As Shape
Dim wheel6 As Shape
Dim wheel7 As Shape
Dim wheel8 As Shape
Dim wheel9 As Shape
Dim wheel10 As Shape
Set wheel1 = ActiveSheet.Shapes("wheel1")
Set wheel2 = ActiveSheet.Shapes("wheel2")
Set wheel3 = ActiveSheet.Shapes("wheel3")
Set wheel4 = ActiveSheet.Shapes("wheel4")
Set wheel5 = ActiveSheet.Shapes("wheel5")
Set wheel6 = ActiveSheet.Shapes("wheel6")
Set wheel7 = ActiveSheet.Shapes("wheel7")
Set wheel8 = ActiveSheet.Shapes("wheel8")
Set wheel9 = ActiveSheet.Shapes("wheel9")
Set wheel10 = ActiveSheet.Shapes("wheel10")
Dim i As Integer, j As Integer, cycle As Integer
Dim winningNumber As Integer
Dim delay As Long
winningNumber = Int((9 * Rnd) + 1)
' 1. Initial Reset
For i = 1 To 10
ActiveSheet.Shapes("wheel" & i).Visible = msoFalse
Next i
' --- STAGE 1: FAST (10 Cycles) ---
delay = 10
For cycle = 1 To 10
For j = 1 To 10
ActiveSheet.Shapes("wheel" & j).Visible = msoTrue
DoEvents
Sleep delay
ActiveSheet.Shapes("wheel" & j).Visible = msoFalse
Next j
Next cycle
' --- STAGE 2: MEDIUM (10 Cycles) ---
delay = 30
For cycle = 1 To 10
For j = 1 To 10
ActiveSheet.Shapes("wheel" & j).Visible = msoTrue
DoEvents
Sleep delay
ActiveSheet.Shapes("wheel" & j).Visible = msoFalse
Next j
Next cycle
' --- STAGE 3: SLOW (10 Cycles) ---
delay = 40
For cycle = 1 To 10
For j = 1 To 10
ActiveSheet.Shapes("wheel" & j).Visible = msoTrue
DoEvents
Sleep delay
ActiveSheet.Shapes("wheel" & j).Visible = msoFalse
Next j
Next cycle
' --- STAGE 4: SLOW (10 Cycles) ---
delay = 50
For cycle = 1 To 10
For j = 1 To 10
ActiveSheet.Shapes("wheel" & j).Visible = msoTrue
DoEvents
Sleep delay
ActiveSheet.Shapes("wheel" & j).Visible = msoFalse
Next j
Next cycle
' --- STAGE 5: SLOW (10 Cycles) ---
delay = 60
For cycle = 1 To 10
For j = 1 To 10
ActiveSheet.Shapes("wheel" & j).Visible = msoTrue
DoEvents
Sleep delay
ActiveSheet.Shapes("wheel" & j).Visible = msoFalse
Next j
Next cycle
' --- FINAL LAP: STOP ON WINNER ---
' Even slower for the "crawl" to the finish line
delay = 70
For j = 1 To winningNumber
ActiveSheet.Shapes("wheel" & j).Visible = msoTrue
DoEvents
Sleep delay
' Only hide if it's not the final winning shape
If j < winningNumber Then
ActiveSheet.Shapes("wheel" & j).Visible = msoFalse
End If
Next j
MsgBox "The wheel stopped on Wheel " & winningNumber & "!"
End Sub
This code is longer and how it works is it determines the winning value at the beginning, based on a random number generator. Then the macro goes through loops to change the visibility of all the wheels, eventually revealing the winning one at the end.
If you liked this post on How to Create a Spinning Wheel in Excel, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on X and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.
If you find yourself performing the same steps over and over in Excel, whether it’s formatting reports, importing data, cleaning up columns, or just about anything else, the Macro Recorder can save you a ton of time. It’s one of Excel’s most powerful automation tools, yet many users overlook it because they think it requires coding knowledge. The truth is, you can create useful macros without writing a single line of VBA code.
In this guide, I’ll cover how to use the Macro Recorder, what you can (and can’t) do with it, and why it’s a great first step into Excel automation.
What Is the Macro Recorder?
A macrois a series of recorded actions in Excel that can be played back to repeat those steps automatically. The Macro Recorder captures your keystrokes, menu selections, and formatting actions in VBA (Visual Basic for Applications) code behind the scenes. It records everything you do in Excel, and then can replay them as a macro later.
How to Turn On the Developer Tab
Before you start recording, you’ll need access to the Developer tab, which is hidden by default. It’s on this tab where you’ll see the button for the macro record and other VBA and developer-related settings.
Go to File → Options → Customize Ribbon.
On the right side, check the box for Developer.
Click OK.
You’ll now see the Developer tab appear on the Ribbon.
How to Record a Macro
Now that you have the Developer tab, enabled, you can easily start using the macro recorder.
Go to Developer → Record Macro.
In the Record Macro window, give your macro a name (no spaces allowed).
Choose where to store it:
This Workbook (saves only in the current file)
Personal Macro Workbook (available across all Excel workbooks)
Optionally, assign a keyboard shortcut (e.g., Ctrl + Shift + R). But be careful to avoid overwriting existing shortcuts.
Add a description so you’ll remember what it does.
Click OK. The recording begins immediately.
Now perform the actions you want Excel to repeat, for example:
Apply formatting to cells
Insert a formula
Create a chart
Copy and paste data
When you’re finished, click on Developer → Stop Recording.
How to Run a Macro
Once you’ve saved your macro, you can easily run it by following either one of these steps:
Press the assigned shortcut key, or
Go to Developer → Macros, select your macro, and click Run.
Excel now repeats every step you recorded, instantly.
PRO TIP: You can also create your own button that launches your recorded macro. To do this, Go to Insert → Shapes, where you can draw your shape or image. After you’re done, right-click on it ,and select the option to Assign Macro. Select your macro. Now, anytime you click the button, the macro will run.
How to View and Edit Your Recorded Macro
All recorded macros are stored in VBA. To see what Excel recorded:
Go to Developer → Macros.
Select your macro and click Edit.
This opens the VBA Editor, showing the code Excel generated. Even if you don’t know VBA yet, this is a great way to learn how your actions translate into code. You might notice patterns like:
With a bit of practice, you can tweak this code to make your macro even more powerful, by adding loops, conditions, or user inputs.
The macro recorder can also be a useful way to find out what the specific syntax is for certain items, such as changing pivot table settings and formatting.
Benefits of Using the Macro Recorder
These are the big advantages of using the macro recorder in Excel:
Saves Time on Repetitive Tasks
Whether you’re formatting monthly reports or importing data, one click can now replace many manual steps.
No Coding Knowledge Required
The recorder handles all the VBA work for you, making it perfect for beginners.
Great Learning Tool
By examining the generated code, you can gradually learn VBA syntax and logic in a real-world context.
Consistency and Accuracy
Recorded macros ensure that repetitive tasks are done exactly the same way every time; no human error, no missed steps.
Drawbacks and Limitations of the Macro Recorder
While the Macro Recorder is powerful, it’s not perfect:
It Records Everything, Even Mistakes
If you make a wrong click, Excel records that too. You’ll either need to start over or clean the code manually later. Code that has used a macro recorder is easy to spot since there will be many unnecessary lines.
Absolute References
By default, macros record exact cell references (e.g., A1, B2). That means if you want the same steps applied to a different range, the macro might not behave as expected.
You can change this by turning on Relative References under the Developer tab before recording.
Limited Flexibility
Macros can’t make decisions or apply complex logic and apply if statements. For that, you’ll need to edit the VBA code directly.
Security Restrictions
Because macros contain code, Excel often disables them by default. Anyone who uses the file will need to enable Macro Settings under File → Options → Trust Center to run them safely.
When to Use the Macro Recorder vs. VBA
Situation
Best Option
You want to automate a short, repetitive sequence (e.g., format a report, clean a dataset)
Macro Recorder
You need logic (loops, conditions, user input) or flexibility
Write or edit VBA manually
You’re just starting to learn automation
Macro Recorder
You want scalable, reusable automation
VBA coding
If you liked this post on How to Use the Macro Recorder in Excel, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.
Have you opened a file in Excel which contains macros in it only to find that you can’t use it, because the content is blocked? If you’ve come across the following warning bar, I’m going to show you how can you remove it once and for all.
This is different than the yellow warning bar in the past where you can just click on Enable Content and be on your way. This fix requires an extra step.
Here’s how to get rid of the red warning bar
1. Close out of the Excel file completely.
2. Right-click on the file and select properties.
3. In the file properties, check off the option to Unblock the file and then click Apply.
4. Re-open the file, where you’ll be back to seeing the more familiar, yellow warning bar where you can select to Enable Content.
Once you click on that button, your file will now be able to run macros.
How can you prevent the red warning bar from popping up in Excel?
If you’re running Windows 11 then every Excel file that you download from the internet will have the red warning bar by default. Even if you send the file to yourself and open it from Outlook, you’ll see that error come up. There is, however, a way to get around it.
Here’s what you can to avoid encountering the red warning bar on macro-enabled Excel files:
In Excel, go to File -> Options
Go to the Trust Center and select Trust Center Settings
Navigate to Trusted Locations
Click on the button to Add new location
Input a location on your computer where you plan to save macro-enabled files and click OK. You can select the option to include subfolders as well.
Any file you save in one of your trusted locations won’t get the red warning bar anymore — you’ll still have the yellow warning bar, however, depending on your macro security settings. But you’ll now able to enable content without having to close and re-open the file.
If you like this post on How to Get Rid of the Red Warning Bar in Microsoft Excel, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.
Excel isn’t a database software but as long as you don’t need to manage millions of data points or have complex, interlocking systems, it can potentially do the job for you — and save you plenty of money. You can create forms, that with the use of visual basic, can populate a database which you can track within Excel and then create reports on later.
Designing a user form and database sheet
Let’s suppose we want to track sales and commission data. A form that someone may fill out could include the following fields:
Sales Rep
Store
Date
Product
Sale Amount
Upon entering this data, a user could click on a button to post the data to another sheet within the workbook, thereby adding it to a database. And with more entries, the data can grow over size. We could then use the data to run reports on and to track store sales, calculate commission, and other metrics.
Here’s how I’ve designed this form in Excel:
The ‘Post Data’ button was created using a shape. And it will be attached to a macro, which will then post to the database worksheet.
Next, I’ll create the corresponding fields where these values will post to on a separate sheet, which I’ll call the database sheet. The layout is a simple one which just involves the same headers from the sales entry form.
Populating the database sheet using a macro
Next, I’ll create a macro to copy the data from the sales entry form to the next row in the database sheet.
The following macro will find the next row in the database sheet, and then copy the values from the sales entry form into the corresponding field. I’ve also added a message box at the end to let the user know that the data was posted successfully to the database sheet. My inputs in cells C4:C8.
Sub copyinputs()
Dim cl As Range
Dim nextrow As Double
Dim wsinput As Worksheet
Dim wsdatabase As Worksheet
'set the worksheet variables
Set wsinput = Worksheets("Input")
Set wsdatabase = Worksheets("Database")
'detect the next available row based on values in column A
nextrow = WorksheetFunction.CountA(wsdatabase.Range("A:A")) + 1
'copy values over
wsinput.Range("C4").Copy wsdatabase.Range("A" & nextrow) ' copy the sales rep
wsinput.Range("C5").Copy wsdatabase.Range("B" & nextrow) ' copy the store
wsinput.Range("C6").Copy wsdatabase.Range("C" & nextrow) ' copy the date value
wsinput.Range("C7").Copy wsdatabase.Range("D" & nextrow) ' copy the product
wsinput.Range("C8").Copy wsdatabase.Range("E" & nextrow) ' copy the sale amount
MsgBox "Posted!"
End Sub
This macro, called copyinputs still needs to be assigned to the button. To do this, I need to right-click on the button on the sales entry form and select Assign Macro and then select this macro. After doing this, I can start entering data and populating my database. When I finish filling in my data and I click on the Post Data button, I get a message saying it has been posted.
And in my database sheet, it has begun populating the data:
As I enter data and click on the Post Data button, it continues adding to my database:
Since it is always calculating the next row, it isn’t overwriting the existing information.
Additional macros to setup
This current macro is a simple one which just posts the data. It doesn’t do anything besides that. It doesn’t check for if the fields are entered nor does it clear them after they’ve been entered. You can adjust this, however, to make the macro and form more robust.
Here’s a macro which includes the existing code plus code to clear the values after they’ve been entered, assuming the values are in the range C4:C8.
Sub copyinputs()
Dim cl As Range
Dim nextrow As Double
Dim wsinput As Worksheet
Dim wsdatabase As Worksheet
'set the worksheet variables
Set wsinput = Worksheets("Input")
Set wsdatabase = Worksheets("Database")
'detect the next available row based on values in column A
nextrow = WorksheetFunction.CountA(wsdatabase.Range("A:A")) + 1
'copy values over
wsinput.Range("C4").Copy wsdatabase.Range("A" & nextrow) ' copy the sales rep
wsinput.Range("C5").Copy wsdatabase.Range("B" & nextrow) ' copy the store
wsinput.Range("C6").Copy wsdatabase.Range("C" & nextrow) ' copy the date value
wsinput.Range("C7").Copy wsdatabase.Range("D" & nextrow) ' copy the product
wsinput.Range("C8").Copy wsdatabase.Range("E" & nextrow) ' copy the sale amount
'clear the data
wsinput.Range("C4:C8").ClearContents
MsgBox "Posted!"
End Sub
Additionally, we can setup rules to make sure that the fields have to be entered fully before clicking on the Post Data button. This can prevent incomplete entries from being posted to the database sheet. Here’s how we can add a code to check if the sales rep field contains a value. This can be repeated for all other required fields:
Sub copyinputs()
Dim cl As Range
Dim nextrow As Double
Dim wsinput As Worksheet
Dim wsdatabase As Worksheet
'set the worksheet variables
Set wsinput = Worksheets("Input")
Set wsdatabase = Worksheets("Database")
'detect the next available row based on values in column A
nextrow = WorksheetFunction.CountA(wsdatabase.Range("A:A")) + 1
'check if the sales rep field contains a value
If wsinput.Range("C4") = "" Then
MsgBox "Please enter a sales rep"
Exit Sub
End If
'copy values over
wsinput.Range("C4").Copy wsdatabase.Range("A" & nextrow) ' copy the sales rep
wsinput.Range("C5").Copy wsdatabase.Range("B" & nextrow) ' copy the store
wsinput.Range("C6").Copy wsdatabase.Range("C" & nextrow) ' copy the date value
wsinput.Range("C7").Copy wsdatabase.Range("D" & nextrow) ' copy the product
wsinput.Range("C8").Copy wsdatabase.Range("E" & nextrow) ' copy the sale amount
'clear the data
wsinput.Range("C4:C8").ClearContents
MsgBox "Posted!"
End Sub
If you like this post on Create a Database Entry Form in Excel to Populate a Sheet Using VBA Macros please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.
Google Sheets provides investors with a great way to pull in stock prices, ratios, and all sorts of information related to stocks. Pulling in a stock’s history, for example, can make it easy for you to calculate a stock’s relative strength index, or create a MACD chart. But doing any sort of analysis for multiple stocks at a time isn’t easy. One way around this is to create a macro using Google App script that can automate the process for you and cycle through multiple stocks. Don’t know how to do it? No problem, because below I’ll provide you with a setup and a code that you can use.
First, I’ll go through creating the file from scratch and how it works.
Setting up the template
In this example, I’m going to find the stock’s largest value for a specific period. To start, I’m going to use the GOOGLEFINANCE function to get the stock history going back to Jan. 1, 2020. In the below example, I’ve got the price history for Meta Platforms, aka Facebook:
In cell B1 I’ve put a variable for the ticker symbol. This is to avoid hardcoding anything in the formula. This is important to make the process easy to update. In the macro, I’m going to cycle through ticker symbols. In Cell E2, I also have a formula that grabs the largest value in column B (the closing price):
=MAX(B:B)
However, this is where you can put your own formula or the results of your own calculation. Whether it’s a minimum, a maximum, or some other computation you want to do, you can put the results of that calculation here. This is the cell that will get copied during the macro.
Then, in column G, I have a list of the stocks that I want the macro to cycle through:
As long as it’s a valid ticker symbol that the GOOGLEFINANCE function recognizes, you can enter it in this column. You can expand it as far as you like. However, if the macro goes on for too long then it will eventually time out and stop. If you want to cycle through every stock in the S&P 500, it is possible, but just be aware that you’ll likely have to do it in chunks. When testing it myself, I estimated I could do somewhere in the neighborhood of 200+ stocks in a single run. Once done, I copied the values onto another place on the spreadsheet with the values, and then replaced the stocks in column G with the next batch.
In Cell J1, I also have a variable called tickercount. This is a helper calculation to make the macro efficient. Instead of it having to count the number of stocks in my list, I provide it for the macro — anything to make it run quicker.
The Apps Script Code
Now it’s time for the code to make this all work. To add code to your Google Sheet, select the Extensions menu and select Apps Script
Once in Apps Script, you can setup a new function. You should see the following:
Here’s the entire code that you can use based on my setup:
function myFunction() {
var sht = SpreadsheetApp.getActiveSheet();
var lastrow = sht.getRange("tickercount").getValue();
for (i=1; i<=lastrow;i++) {
//change ticker
sht.getRange('B1').setValue(sht.getRange('G' + i).getValue());
//copy maximum value
var result = sht.getRange('result').getValue();
sht.getRange('H' + i).setValue(result);
}
}
Here’s a brief explanation of how the code works:
It begins by selecting the active sheet.
It determines the last value based on the ‘tickercount’ named range.
It loops through the values in column G.
It takes the value in column G and pastes it into cell B1 (the ticker variable).
The macro then gets the value from cell E1 (it has a named range called ‘result’)
It pastes the value of the result into column H, to the same row that the stock ticker was on.
If you leave my setup the way it is, what you can do is do any of your desired calculations on another part of the worksheet. As long as it doesn’t interfere with the ticker list or any of the ranges used in the macro, then you’re fine. You can also adjust where the cells are if that makes it easier. For example, you could move the ‘result’ named range from E1 to somewhere else in the spreadsheet. With a named range, you don’t need to worry about updating the cell reference.
Running the macro
A final part of this macro is actually running it. You need a way to trigger it. In my example, I’m using a button. This makes it easy to see what you need to click on for the macro to run. Here’s how you can create a button in Google Sheets and assign a macro to it:
1. Go to Insert and select Drawing
2. Create a shape, add text to it, and whatever colors/formatting you want. Then click Save and Close.
3. Select the button and click on the three dots on the right-hand side, where you will see an option to Assign Script.
4. In the following dialog box, enter the name of your function (don’t include the parentheses). The default function in Apps Script is called myFunction() and if that’s the macro you want to use, then you would just enter myFunction and click on OK.
If everything works, now when you click on your button, the macro will run. Check for any error messages to see if you run into any issues. If you need to edit the button afterwards, right-click on it first so that you don’t accidentally trigger the macro.
One thing to note is that when you run a macro on a Google Sheets file for the first time, you’ll be given a warning about doing so:
Click on Review permissions and select your Google account. You’ll get the next warning, saying that Google hasn’t verified this app and you’ll need to click on Advanced to continue despite the warnings. This is similar to the warnings you encounter in Microsoft Excel when enabling macros. Once you proceed and click on Allow, the macro will proceed to run.
Here’s how it looks in action:
Download my loop macro template
If you’ve gone through this post and run into issues or it is too complicated for you, feel free to download my loop macro template. Since it’ll create a copy for your use, you can modify it however you like to suit your needs.
If you like this post on Loop Through Stocks in Google Sheets With a Macro, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.
If you need to reference other files or folders within an Excel sheet, trying to predict what the path will be can be challenging. The easier option is to just have the user select the file or folder from their computer, and then have the path get pasted into a cell. To do this, you will need to use visual basic (VBA) for Excel to be able to get this value for you. In this post, I’ll show you how you can do that.
Creating the VBA code to select a file or folder
There are a couple of variables that need to be setup for this code. One is for the file or folder selection, and the other for the actual path. In the below example, I’m going to use the folder picker option. I’ll also disallow multiple selections to ensure the path value can easily be pasted into Excel:
Dim folder As FileDialog
Dim path As String
Set folder = Application.FileDialog(msoFileDialogFolderPicker)
folder.AllowMultiSelect = False
If folder.Show = -1 Then
path = folder.SelectedItems(1)
End If
If path = "" Then Exit Sub
If Right(path, 1) <> "\" Then path = path & "\"
Range("mypath") = path
The folder.show = -1 line is simply to make sure that the user has clicked the button. And if they do, the macro will just pull in the path of the selected item (since multiple selections are disallowed). Towards, the end of the code, there is also a backslash that is added in case it isn’t included within the path. If you were dealing with a file selection, this wouldn’t be necessary.
The last line of code assigns the path to a named range in your spreadsheet called ‘mypath’. You will need to create this to ensure the path goes to the right cell.
The above code will work just as well if you need to select a single file. The only difference is rather than referencing the msoFileDialogFolderPicker, you would want to access the msoFileDialogFilePicker. You can also remove the line that adds the backslash. And you would probably want to change the name of the variable from folder to file.
Create a button to run the macro
One thing you’ll want to do when setting up this macro is to add a button. This way, the user can just click the location next to where the path will be go. To create a button in Excel, go to the Insert tab. Then, select the drop-down menu for Shapes, and then select a square or rectangle to create a button. Once you have created it, right-click and select Edit Text. Here, you can type in a description for the button, such as Select Folder. Next, you can right-click the button and select Assign Macro. Then you should see the following dialog box, where you can select the macro you just created:
Once you’ve assigned the macro, you will be able to just click it so that it runs.
Selecting multiple file and folder paths
If you want to have the user select multiple paths, the easiest solution is just to have multiple places where you can select files or folders. The good news is you don’t need to create multiple macros for this. Instead, you just need to modify the code so that it looks at which row the button you click on is in. This requires using the application caller. Instead of using a named range, I’ll refer to a set column and the row that the button is on. To adjust the macro, I need to add a variable for the selectedRow and assign its value as follows:
Dim selectedRow as integer
selectedRow = Activesheet.Shapes(Application.Caller).TopLeftCell.Row
Assuming that I want to put the path in column A, this will now be my last line of code:
Range("A" & selectedRow) = path
Here is the full code:
Sub selectfolder()
Dim folder As FileDialog
Dim path As String
Dim selectedRow As Integer
Set folder = Application.FileDialog(msoFileDialogFolderPicker)
folder.AllowMultiSelect = False
selectedRow = ActiveSheet.Shapes(Application.Caller).TopLeftCell.Row
If folder.Show = -1 Then
path = folder.SelectedItems(1)
End If
If path = "" Then Exit Sub
If Right(path, 1) <> "\" Then path = path & "\"
Range("A" & selectedRow) = path
End Sub
Since it looks at the selected row, you can just copy the button to multiple rows. You don’t need to create a different macro. However, since it looks at the top left cell, it’s important to keep the button within just a row. Don’t let it bleed into another row. Otherwise, you may populate the path into the wrong cell. Here’s how the buttons look in my example:
It doesn’t matter if the buttons span multiple columns. Using the code above, they simply shouldn’t be extending into another row. In the above example, I have just copied the button multiple times. Now, when a user click on them and makes a selection, it will paste the selected path into the corresponding cell in column A.
If you liked this post on How to Use VBA Code So a User Can Select a File or Folder Path, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow us on Twitter and YouTube.
You can add lots of automation to your spreadsheet by utilizing visual basic (VBA) and running macros. One of the more common macros you might run include loops. In particular, using for loops in VBA can allow you to cycle through a range of data, check for criteria, and then execute commands. Or, you can also use it to do calculations and to compute totals. There’s a lot of potential with running loops in VBA. In this post, I’ll show you how you can get started with them.
Looping through data in Excel to highlight blank or incomplete data
In the following data set, I have some missing values where there is an (*) in place of a value in column D:
I’m going to loop through the column that shows the change value and I will look for the (*) values.
To get started, launch VBA from the developer tab or hit ALT+F11. Then, insert a new module. I’m going to call this subprocedure ‘cleanup’. I’ll start with declaring variables for the worksheet, individual cell I’m looping through, an integer to track how far along I am in the range, and an integer for the last cell within the range.
Sub cleanup()
Dim ws As Worksheet
Dim cl As Range
Dim lastcell As Integer
Dim i As Integer
Set ws = ActiveSheet
lastcell = ws.Range("A1").SpecialCells(xlCellTypeLastCell).Row
End Sub
In the above code, I’ve assigned the worksheet variable to the sheet that I’m on. And I set the lastcell variable to the last row in the sheet. This is the same as if you were press F5->Special->Last Cell. This makes it easy to determine where the data set ends, and gives me an endpoint for my loop. There are other types of loops you can use where you don’t need to specify an end. But this reduces the risk of you getting into a never-ending loop.
As for the loop itself, it will look like this:
For i = 1 To lastcell
Set cl = ws.Range("D" & i)
If cl = "(*)" Then
cl.EntireRow.Interior.Color = vbRed
End If
Next i
How it works is it uses the i variable to start from 1 and go all the way until the lastcell variable. In this example, that relates to 92 (the last row in my data set).
Then, it assigns the cl variable to each cell in column D as I go through that range. In the first instance, the cl variable is D1, then D2, and so on, until you reach the end (D92).
Next, it evaluates if the value of that cell is (*). If it is, then it highlights the entire row in the color red. If I run this macro, this is what my sheet looks like afterwards:
It did the job well, as you’ll notice everything that had a value of (*) in column D, the entire row ended up getting highlighted in red. There are other colors you can use and other things you could have done. Next, I’ll show you how you can just delete these rows entirely.
Deleting rows while looping through data in Excel
Removing rows seems simple enough, but it is a little tricky here. For instance, to remove the row rather than to just highlight it, that involves a simple line of code (in my example I’m referring to my cl variable):
cl.EntireRow.Delete
If I run the macro with that code, this is what happens to my worksheet:
I’ve left the red highlighting in place to show you that there are still many rows that should have been deleted and that weren’t. So did the macro simply not work?
The problem lies with how it was set up. In the current macro, I’m moving down from one row to the next. If I’m at row 10 and delete it, then the next row I move on to is row 11. However, the issue is that once I delete row 10, everything moves up a spot. So what was previously row 11 now becomes row 10, causing me to effectively skip over that row and miss it. Now my macro no longer evaluates it.
There are a couple of ways to fix this. One can be that if I delete the row, I can adjust my i variable so that it deducts one so as not to skip over the next row. Just by adding a line of code, you can adjust for that issue:
For i = 1 To lastcell
Set cl = ws.Range("D" & i)
If cl = "(*)" Then
cl.EntireRow.Delete
i = i - 1
End If
Next i
The i = i -1 line of code will reset the i variable back down a spot when a row is deleted. This will now prevent the macro from jumping over a row.
However, there’s another option you can use, and that’s looping through the data in the opposite direction.
Looping through the data backwards and utilizing the step keyword
In the first example, I looped through the data from row 1 to the last row. Here’s my full code for that:
Sub cleanup()
Dim ws As Worksheet
Dim cl As Range
Dim lastcell As Integer
Dim i As Integer
Set ws = ActiveSheet
lastcell = ws.Range("A1").SpecialCells(xlCellTypeLastCell).Row
For i = 1 To lastcell
Set cl = ws.Range("D" & i)
If cl = "(*)" Then
cl.EntireRow.Delete
End If
Next i
End Sub
I’m going to adjust this and go in reverse order. However, it’s not as simple as specifying start from the bottom number and go to row 1. You need to give VBA a bit more information. This is where you can use the Step keyword. By using that, you can specify in which direction you want the loop to go, and whether it should go 1 row at a time or jump multiple rows.
Here’s how the loop looks like if I want VBA to jump backwards one row at a time from the bottom:
For i = lastcell To 1 Step -1
Set cl = ws.Range("D" & i)
If cl = "(*)" Then
cl.EntireRow.Delete
End If
Next i
If you want to jump by 5 rows, you would use Step -5. However, because I want to evaluate each row, -1 is what I’ll use in this example. By running this loop, now the highlighted rows are all deleted:
Since the loop is starting from the bottom and working its way up, it doesn’t matter that I’m deleting rows; it doesn’t impact the rows above and so no adjustment to the i variable is necessary.
If you like this post on How to Create For Loops in VBA, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow us on Twitter and YouTube.
Dashboards in Excel can update when a user makes a selection on a slicer or refreshes data. You can even use macros to automatically update a chart or dashboard for you. In this post, I’ll share with you a template that I’ve created that will allow you to effectively play your dashboard, updating it from one period to the next, and showing the change in the chart over time. Here it is in action:
The template has three sections: one for pivot tables, one for the data, and one for the dashboard. You can set the file up however you want, the main area that needs to remain largely the same is the dashboard sheet. Every chart on this sheet only will automatically get updated. And for it to work properly, all the charts need to be linked to the one timeline chart in here (i.e. there cannot be more than one). For information on how to set up your timeline (or any other slicer for that matter) so that you can link it to multiple charts, you’ll need to learn about how to adjust Report Connections in this post.
Once you’ve got the charts you want to be connected to the timeline, then it’s a matter of just updating the settings section on the Dashboard tab. This is off to the left, with the values that you need to enter/update highlighted in yellow.
These simply specify what date you want to start from, where you want to end at, and by which interval you want to jump (e.g. x days/months/years). Depending on the frequency you select, your dashboard can either play very quickly, or very slowly.
The last step is to just click the Animate Dashboard button at the end of the home tab:
Upon clicking this, the timeline will jump by the intervals you specified. No other changes will be made to any filters or slicers you have selected. The only changes will take place to the timeline, at which point, you should see something similar to the video posted at the top of this post.
If you liked this free template that helps you animate your dashboards, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow us on Twitter and YouTube.
In a previous post, I went over how to modify the Excel ribbon with some basic buttons. This time, I’m going to focus specifically on a toggle button that can change the value of a cell or trigger a calculation or macro. In this example, I’ll show you how you can create a toggle button on the ribbon that will change the color of the sheet, switching between having no fill and a white fill.
The first thing you’ll want to do is download the CustomUI Editor, which you should be able to find online through a search. Once you have that, you can get to work on coding the xml.
Creating the ribbon code
To get started, you can refer to this post on how to create a simple tab and button on the Excel ribbon. Once you have that basic framework set up in the CustomUI Editor, it’s just a matter of modifying the type of button you’ll use. In that post, I just inserted some generic code for a button:
The button in that example is just a basic button. To turn it into a toggle button, I just need to modify the syntax so rather than saying ‘button’ it says ‘toggleButton’. I still need a label, an image, and specify what happens when it is pressed (the ‘onAction’ argument). Here’s what my updated xml code looks like:
Changing button to toggleButton just allows the button to have a pressed state so that when you click on it, it can look sunken. You can use that variable to also dictate what action should be taken. The key to making the toggle button work is to attach some macros to it, which is what I’ll cover next.
Creating the callback macros
A callback macro tells Excel what should happen when the toggle button is clicked. Here’s what the macro should look like initially:
Sub Callback(control As IRibbonControl, pressed As Boolean)
End Sub
The pressed value is a boolean, so it will only either be true or false. The next part of the code involves setting up an if statement to check on that value.
If pressed = True Then
'code goes here if the value is true (pressed)
Else
'code goes here if the value is false (not pressed)
End If
In this example, I’m going to make a simple macro where the sheet is either filled white, or there is no fill effect. The code isn’t complicated and I will start will selecting all the cells, selecting the interior property, and setting it to solid (i.e. ‘filled’):
Cells.Interior.Pattern = xlSolid
And to change it back so there is no fill effect:
Cells.Interior.Pattern = xlNone
Within the full callback macro, this is how all the code looks:
Sub Callback(control As IRibbonControl, pressed As Boolean)
If pressed = True Then
Cells.Interior.Pattern = xlSolid
Else
Cells.Interior.Pattern = xlNone
End If
End Sub
Here is the toggle button in action:
If you liked this post on How to Create a Toggle Button on the Excel Ribbon, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow us on Twitter and YouTube.