You spend 5 hours every week copying data between Excel files, updating reports and sending the same report to 15 different recipients. With VBA you can automate all of this. Here is how.

During my ten years as an Excel consultant I have seen companies save hundreds of hours every month by automating their Excel workflows. These are not theories from a textbook – these are real solutions that my team and I have built for clients ranging from Volvo to small businesses in Stockholm.

In this guide you get a complete introduction to VBA (Visual Basic for Applications), Excel’s built-in programming language. Whether you have never written a line of code or already know a little VBA, you will get concrete tools for automating your most time-consuming tasks.

Why automate Excel?

Before we dive into the technology we need to talk about why. I often meet finance directors and controllers who say “we’re doing fine as it is”. Then we discover that their team spends 15-20 hours every month on manual work that a macro would do in 30 seconds.

The time savings are real and measurable

When a client contacted us about their monthly reporting, three people spent every month-end compiling data from 47 different Excel files. The process took two full days. We built a VBA solution that did the same thing in 12 minutes. That is 48 working hours saved every month.

Calculate for your own situation: if you spend 2 hours a week on a repetitive task, that is 104 hours per year. With a labour cost of SEK 500 per hour we are talking about SEK 52,000 annually – for ONE task. Most people have several such processes.

Fewer errors make a bigger difference than you think

People make mistakes, especially with repetitive tasks. You copy from the wrong cell, forget to update a formula, send the wrong version to the client. One of our clients in the accounting industry discovered that manual data transfers led to errors in about 3% of entries. That sounds small, but when you handle thousands of transactions it becomes a significant problem.

VBA code does exactly the same thing every time. If you program it correctly the first time, you get consistently correct results. Yes, you can have bugs in the code – but once they are fixed, they stay fixed.

Scalability becomes possible

When your business grows, Excel usage often grows too. Suddenly you don’t have 5 files but 50. Not 100 rows but 10,000. Manual processes that worked three years ago become impossible to maintain.

I worked with a growing e-commerce company that handled order data in Excel. When they had 50 orders a day, manual handling worked. At 500 orders the system collapsed. Their solution was to hire more people for data processing. Our solution was a VBA system that handled 5,000 orders as easily as 50.

The team gets to do what they are good at

This is perhaps the most underrated benefit. Your colleagues were not trained to copy data between files for five hours. They were trained for analysis, strategy, client contact.

When we automate repetitive work, we free up capacity for what actually creates value. A finance professional who spends 10 hours less on report production has 10 more hours to analyse the figures and give recommendations.

At Excel Department we see automation as an investment, not a cost. The initial time investment to build a VBA system pays back quickly, and keeps delivering value year after year.

VBA for beginners – The basics

VBA stands for Visual Basic for Applications. It is Microsoft’s programming language built into the whole Office suite, but used mostly in Excel. Think of it as Excel’s engine bay – the surface is the spreadsheet you see, but underneath there is an engine where you can program almost anything.

Where do you find the VBA editor?

Press Alt + F11 in Excel and the VBA environment opens. Here you see three main areas: the project explorer on the left (showing your workbooks and modules), the properties window below it, and the large code editor in the middle.

If you don’t see the Developer tab in the menu bar: go to File > Options > Customize Ribbon and tick “Developer”. From there you can also open the VBA editor, record macros and manage security settings.

Your first macro

Your first macro can be as simple as this:

Sub MittFörstaMakro()
    MsgBox "Hej! Det här är ditt första VBA-makro."
End Sub

Enter the code in a module (Insert > Module in the VBA editor), press F5 or click the play button. A dialog box appears with your message. Congratulations – you have written and run VBA code.

If you want a more detailed walkthrough of how to create your first macro step by step, I recommend our guide VBA for Beginners: Your First Macro in 15 Minutes.

Basic syntax

Basic syntax follows clear patterns. Every macro starts with Sub (for “subroutine”) followed by a name and parentheses. It ends with End Sub. Everything in between is code that runs from top to bottom.

Sub ExempelPåSyntax()
    ' Det här är en kommentar (förklarande text)
    Dim mittvärde As Integer  ' Deklarerar en variabel
    mittvärde = 42            ' Tilldelar ett värde

    ' Skriv till cell A1
    Range("A1").Value = mittvärde

    ' Villkor
    If mittvärde > 40 Then
        MsgBox "Värdet är större än 40"
    End If
End Sub

Some important concepts:

  • Range refers to cells (Range(“A1”), Range(“B2:B10”))
  • Cells is an alternative way using row/column (Cells(1,1) = A1)
  • Dim declares variables (storage space for data)
  • If/Then/Else handles conditions
  • For/Next and Do/Loop are used for repetition

The macro recorder vs manual coding

Many people start with the macro recorder (Developer > Record Macro). You perform actions in Excel, and the recorder saves them as VBA code. It is useful for seeing how things translate into code, but recorded code is often messy and inefficient.

I recommend using the recorder to learn syntax, then rewriting the code by hand. When you record “select cell A1, make it bold, type ‘Hello’” you may get 15 lines of code. The same thing can be done in 2 lines of hand-written code.

In our Excel courses we always spend the first hour on exactly the basics: the VBA environment, simple syntax, the difference between objects and methods. That knowledge is the foundation for everything else.

The object model

The object model is VBA’s logical structure. Application (Excel itself) contains Workbooks, which contain Worksheets, which contain Range objects (cells). Each level has properties (values) and methods (actions).

' Objekthierarki i praktiken
Application.Workbooks("Rapport.xlsx").Worksheets("Jan").Range("A1").Value = 100

You don’t need to write out the whole hierarchy every time – VBA understands context. But understanding the structure helps enormously when you troubleshoot or build advanced solutions.

The most important lesson for beginners: start simple. Don’t try to build a complex system from day one. Build a macro that does one thing, get it working, understand every line of code. Then build on it.

Top scenarios for Excel automation

After thousands of consulting hours I have seen which tasks truly benefit from automation. Here are the scenarios where VBA has the greatest impact. For a more detailed walkthrough you can read our article The 10 Most Common Excel Tasks You Can Automate Today.

1. Data import from external sources

How often do you copy data from CSV files, text files or other Excel files into your main report? With VBA you automate the whole flow.

Sub ImporteraCSV()
    Dim filnamn As String
    Dim ws As Worksheet

    ' Välj fil
    filnamn = Application.GetOpenFilename("CSV-filer (*.csv), *.csv")

    If filnamn <> "False" Then
        ' Skapa nytt blad för import
        Set ws = ThisWorkbook.Worksheets.Add
        ws.Name = "Importerad Data"

        ' Öppna och importera CSV
        With ws.QueryTables.Add(Connection:="TEXT;" & filnamn, _
            Destination:=ws.Range("A1"))
            .TextFileParseType = xlDelimited
            .TextFileCommaDelimiter = True
            .Refresh BackgroundQuery:=False
        End With

        MsgBox "Import klar!"
    End If
End Sub

This code lets the user choose a CSV file, creates a new sheet and imports data with correct formatting. No manual copying, no pasted values that suddenly turn into text instead of numbers.

2. Repetitive reporting

Monthly reports that always follow the same structure are perfect for automation. We built a system for a finance client where one button generates a 40-page report with charts, tables and analysis based on the latest month’s data.

For a complete guide on how to automate your reports, read our article Automate Excel Reports: Step by Step with VBA.

3. Email directly from Excel

A scenario I see often: you have a customer list in Excel and need to send personal emails to each customer. Manually it takes hours. With VBA it takes minutes.

Sub SkickaPersonligaEmail()
    Dim OutlookApp As Object
    Dim Mail As Object
    Dim ws As Worksheet
    Dim sistaRad As Long
    Dim i As Long

    Set ws = ThisWorkbook.Worksheets("Kunder")
    sistaRad = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    Set OutlookApp = CreateObject("Outlook.Application")

    For i = 2 To sistaRad
        Set Mail = OutlookApp.CreateItem(0)

        With Mail
            .To = ws.Cells(i, 2).Value  ' Email i kolumn B
            .Subject = "Hej " & ws.Cells(i, 1).Value
            .Body = "Hej " & ws.Cells(i, 1).Value & "," & vbCrLf & _
                    "Ditt kundsaldo är: " & ws.Cells(i, 3).Value
            .Send
        End With

        Set Mail = Nothing
    Next i

    Set OutlookApp = Nothing
    MsgBox "Skickade " & (sistaRad - 1) & " email"
End Sub

Note that this example actually sends the emails. For testing, replace .Send with .Display so the email opens instead of being sent directly.

4. Formatting and standardisation

You receive data from different departments and everyone formats differently. A macro can standardise everything in seconds – fonts, colours, column widths, decimals, date formats.

5. Data validation and cleaning

Large datasets always contain problems: duplicates, misspellings, empty cells where there should be values. VBA can scan thousands of rows and flag or fix problems automatically.

6. Integration with other systems

VBA can talk to databases (Access, SQL Server), web services, other Office programs and even external APIs. That makes Excel a powerful hub in your data ecosystem.

How to build your first real macro

Now we build something practical: a macro that cleans and formats monthly sales data. This is the kind of task I see every week at clients.

Step 1: Define the problem

Before you write code you need to know exactly what should happen. Write down the steps:

  1. Remove empty rows
  2. Format the header row (bold, blue background, white text)
  3. Format number columns with thousands separators
  4. Add a totals row at the bottom
  5. Adjust column widths

Step 2: Open the VBA editor and create a module

  1. Press Alt + F11
  2. In the menu, choose Insert > Module
  3. Now you have a blank window where you can write code

Step 3: Write the macro step by step

Sub FormateraFörsäljningsData()
    Dim ws As Worksheet
    Dim sistaRad As Long
    Dim i As Long

    ' Referera till aktivt blad
    Set ws = ActiveSheet

    ' Hitta sista raden med data i kolumn A
    sistaRad = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    ' STEG 1: Ta bort tomma rader
    For i = sistaRad To 2 Step -1
        If Application.WorksheetFunction.CountA(ws.Rows(i)) = 0 Then
            ws.Rows(i).Delete
        End If
    Next i

    ' Uppdatera sista raden efter borttagning
    sistaRad = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    ' STEG 2: Formatera rubrikrad
    With ws.Range("A1:E1")
        .Font.Bold = True
        .Interior.Color = RGB(68, 114, 196)
        .Font.Color = RGB(255, 255, 255)
        .HorizontalAlignment = xlCenter
    End With

    ' STEG 3: Formatera sifferkolumner (kolumn D och E)
    ws.Range("D2:E" & sistaRad).NumberFormat = "#,##0"

    ' STEG 4: Lägg till summeringsrad
    ws.Cells(sistaRad + 1, 1).Value = "TOTALT"
    ws.Cells(sistaRad + 1, 1).Font.Bold = True

    ws.Cells(sistaRad + 1, 4).Formula = "=SUM(D2:D" & sistaRad & ")"
    ws.Cells(sistaRad + 1, 5).Formula = "=SUM(E2:E" & sistaRad & ")"

    ' STEG 5: Anpassa kolumnbredder
    ws.Columns("A:E").AutoFit

    MsgBox "Formatering klar! Bearbetade " & (sistaRad - 1) & " rader."
End Sub

Step 4: Test the macro

Before you run the macro on real data:

  1. Create a copy of your sheet (right-click the sheet tab > Move or Copy > tick “Create a copy”)
  2. Run the macro on the copy (F5 in the VBA editor)
  3. Check the result carefully
  4. If something is wrong, adjust the code and test again

Step 5: Make the macro available

You can run the macro in several ways:

Option 1: Add a button 1. Go to Developer > Insert > Button (Form Control) 2. Draw the button where you want it 3. Choose your macro from the list 4. Right-click the button > Edit Text to rename it

Option 2: Assign a keyboard shortcut 1. Go to Developer > Macros 2. Choose your macro 3. Click Options 4. Assign a keyboard shortcut (e.g. Ctrl+Shift+F)

Option 3: Add to the Quick Access Toolbar 1. File > Options > Quick Access Toolbar 2. Choose “Macros” in the dropdown 3. Choose your macro and click Add

Now anyone on the team can run the formatting with the push of a button.

Advanced VBA techniques

Once you master the basics, advanced possibilities open up. Here are some techniques that take your macros to the next level.

Userforms – Create your own user interface

Userforms let you build dialog boxes with text fields, buttons, list boxes and more. Instead of changing the code, the user can enter values in an interface.

Example: A userform for report generation where the user chooses date range, department and report type from dropdowns. The macro then uses these values to create the right report.

Error handling – Handle problems elegantly

Professional macros handle errors without crashing:

Sub RobustMakro()
    On Error GoTo FelHantering

    ' Din kod här
    Dim resultat As Double
    resultat = 100 / 0  ' Detta ger ett fel

    Exit Sub

FelHantering:
    MsgBox "Ett fel uppstod: " & Err.Description
    ' Logga felet, skicka notifiering, etc.
End Sub

Performance optimisation

Slow macros are often caused by Excel updating the screen and recalculating after every change. Turn this off temporarily:

Sub SnabbtMakro()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    ' Din kod här (kan vara tusentals operationer)

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub

This technique can make macros 10-100 times faster.

Working with external files

You can open, read and write to other Excel files without the user seeing them:

Sub HämtaFrånAnnanFil()
    Dim wbKälla As Workbook
    Dim värde As Variant

    ' Öppna utan att visa
    Set wbKälla = Workbooks.Open("C:\Data\Försäljning.xlsx", ReadOnly:=True)

    ' Hämta värde
    värde = wbKälla.Worksheets("Data").Range("A1").Value

    ' Använd värdet i din arbetsbok
    ThisWorkbook.Worksheets("Import").Range("A1").Value = värde

    ' Stäng utan att spara
    wbKälla.Close SaveChanges:=False
End Sub

Database integration

VBA can connect to SQL databases, which makes Excel a powerful front end for database data:

Sub HämtaFrånDatabas()
    Dim conn As Object
    Dim rs As Object

    Set conn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")

    ' Anslut (exempel med SQL Server)
    conn.Open "Provider=SQLOLEDB;Data Source=server;Initial Catalog=databas;User ID=user;Password=pass"

    ' Kör query
    rs.Open "SELECT * FROM Kunder WHERE Land = 'Sverige'", conn

    ' Skriv resultat till Excel
    ActiveSheet.Range("A2").CopyFromRecordset rs

    rs.Close
    conn.Close
End Sub

Common pitfalls and how to avoid them

After ten years of VBA development I have seen the same mistakes over and over again. Here is how to avoid them.

Pitfall 1: No planning before coding

Many people jump straight into the VBA editor and start writing. The result is messy code that is hard to maintain.

Solution: Write down in plain English what the macro should do, step by step. Then translate each step into code. Your commented pseudocode becomes your guide.

Pitfall 2: No comments

“I’ll remember what the code does.” You won’t in six months when something needs to be changed.

Solution: Comment liberally. Explain WHY, not just what. “Loops backwards so deletion works” is better than “Loop”.

Pitfall 3: Hardcoded values

' Dåligt exempel
Range("A1:E100").Copy

What happens when your data grows to 150 rows?

Solution: Use dynamic references:

' Bra exempel
sistaRad = Cells(Rows.Count, "A").End(xlUp).Row
Range("A1:E" & sistaRad).Copy

Pitfall 4: Not testing on a small dataset first

Running an untested macro on 50,000 rows of production data is a recipe for disaster.

Solution: Always test on a small subset first (100 rows). When it works there, scale up.

Pitfall 5: Ignoring security

Macros from unknown sources can contain malicious code. Even your own macros can cause damage if they are run by mistake.

Solution: – Enable only macros from trusted sources – Add confirmation dialogs before destructive operations – Use digital signatures for company macros – Read our guide on Excel macro security for more information

Pitfall 6: No version control

“Version_3_final_really_final_THIS.xlsm” is not version control.

Solution: Export your modules regularly (right-click the module in the VBA editor > Export File). Save them in a folder with a date stamp. Even better: use Git for version control.

When you should hire a VBA consultant

Self-teaching takes you far, but some situations call for professional help. Here is when you should contact an expert.

Complex business-critical systems

If your automation handles financial transactions, customer data or regulatory compliance, you want it done right from the start. The cost of errors can far exceed the cost of a consultant.

We helped an accounting firm build a VBA system for VAT reporting. An error there could have cost them hundreds of thousands of kronor in penalties. Professional development, testing and documentation were well worth the investment.

Lack of time

If you have identified 20 hours of work that could be automated, but it takes 40 hours to learn VBA and build the solution yourself, it is often more economical to hire help.

A VBA consultant can build in a week what takes you two months to learn.

Integration with complex systems

Database integrations, API calls, integration with ERP systems – this requires specialist expertise. If you are not a programmer, the learning curve will be very steep.

Performance problems

You have built a macro but it takes 10 minutes to run. An experienced developer can often optimise it to under a minute using techniques you are not familiar with.

Maintenance and further development

Someone built a complex VBA system three years ago. That person has left. Nobody understands the code. Now you need to change something.

We see this often. Professionally written, documented code with a modular structure is much easier to maintain and develop further.

ROI of Excel automation

Let’s calculate concretely what automation is worth.

Scenario: You have a monthly report that takes 4 hours to create manually.

  • Manual time per year: 48 hours
  • Labour cost (SEK 500/h): SEK 24,000/year
  • Development cost for VBA solution: SEK 20,000 (one-off cost)
  • New time with automation: 15 minutes/month = 3 hours/year
  • Annual saving: 45 hours = SEK 22,500

Payback time: 0.9 years (less than a year)

Value over 5 years: SEK 112,500 – SEK 20,000 = SEK 92,500 in savings

And that is just ONE report. Most organisations have many such processes.

But the real value is not just the hours saved. It is what the team can do with that time instead. Deeper analysis. Better customer service. Strategic work.

We helped a finance department save 15 hours per week through automation. They didn’t hire fewer people – instead they were able to start projects that had been on ice for two years due to lack of time.

Next step – Get started with Excel automation

You now have the basics to start automating your Excel workflows. Here is how to take the next step.

For those who want to learn by themselves

  1. Start small: Choose ONE simple task that takes 10-15 minutes every day. Build a macro for it.
  2. Use the recorder: Record the task, study the code, rewrite it more neatly.
  3. Explore our guides: We have detailed tutorials for common scenarios – VBA for beginners, automating reports, and more.
  4. Take a VBA course: Structured training gives you the fundamentals faster than self-study.

For those who want help

If you have identified automation opportunities but lack the time or skills to carry them out yourself, we are happy to help.

Excel Department offers:

  • Free consultation (15 min): We discuss your needs and assess whether automation is the right solution
  • Tailor-made VBA solutions: We build systems adapted to your exact processes
  • Training for your team: Group courses where you learn to build and maintain your own macros
  • Support and maintenance: We are here even after the solution has been delivered

How it works:

  1. You book a short call where we talk about your challenges
  2. We assess the potential (we often find 50-100 hours/year to save)
  3. We propose a solution – either we build it for you or train your team
  4. You receive a fixed quote before we start
  5. We deliver, test and document the solution
  6. You save time and can focus on what actually creates value

Real client results

Case 1 – Finance company in Stockholm: Automated the monthly consolidation report. Saved 20 hours/month. Read the full case: Client Case: Automated Reporting Saved 20 Hours/Week.

Case 2 – Accounting firm: Automated data import from clients’ various systems. Saved 12 hours/week in manual data handling.

Case 3 – E-commerce company: Automated order processing and inventory reporting. Enabled 300% growth without hiring more administrative staff.

Frequently asked questions about VBA and Excel automation

Is VBA hard to learn? You learn the basics in a couple of days. Becoming really good takes a few months of regular practice. It is easier than most programming languages because it is built specifically for Excel.

Can VBA replace Excel formulas? No, and it shouldn’t. Use VBA for automation and repetitive tasks, use formulas for calculations that users should be able to follow. Often you combine both.

Is VBA a dying technology? Should I invest in Python instead? VBA is far from dead. Hundreds of millions of people use Excel every day, and VBA is built in. For Excel-specific automation, VBA is still the most efficient choice. Python is powerful for data analysis but has a steeper learning curve for Excel integration. Read more: VBA vs Power Query.

How secure are VBA macros? Macros from unknown sources can contain malicious code. Enable only macros from trusted sources. Your own macros are safe – they only do what you program them to do. Read our guide on Excel macro security.

Can I use VBA in Excel Online? No, VBA only works in Excel for Windows and Mac (desktop versions). Excel Online does not support macros. Office Scripts is Microsoft’s new automation solution for the web, but it is considerably more limited.

What is the difference between VBA and a macro? A macro is an automated series of actions. VBA is the language you write macros in. When someone says “I have a macro” they usually mean VBA code that automates something.

Summary – Automation as a competitive advantage

Excel automation with VBA is not just a technical nicety – it is a strategic competitive advantage. While your competitors spend hours on manual work, your team has already analysed the results and made decisions.

Remember: – VBA is accessible to everyone – you don’t need a programming background – Start with small projects and build skills step by step – ROI comes quickly – often within a few months – When it gets complex, expert help is available

At Excel Department we have helped hundreds of companies automate their Excel processes. We have seen the effects: freed-up time, fewer errors, scalable growth and teams that get to focus on value-creating work instead of manual data handling.

Are you ready to take the next step?

Book a free consultation – we discuss your automation opportunities and show you how much time you can save.

Or start on your own with our VBA course for beginners where you learn the basics in one day.

Automation starts with a single macro. That macro can be the beginning of a transformation in how your team works with data.


Written by Lukas Lilja, founder of Excel Department. With over ten years of experience in Excel consulting and VBA development, we help Swedish companies automate, streamline and grow.

Need help with this? Our VBA course can help you – the first consultation is free.

Book a free call or call 010-264 20 20.