Automate Excel With ChatGPT and VBA
I asked ChatGPT to write four Excel macros: consolidate data from a folder of workbooks, draft personalized Outlook emails with attachments, find and replace text across files, and build a pivot table with a chart. All four worked after small fixes, so some VBA knowledge still helps.
Consolidate data from many files
The first macro collects three values from every workbook in a folder into one summary sheet. ChatGPT wrote working code on the first try.
My input folder holds files with the same structure: a “Settings” sheet and a “Data” sheet. The Settings sheet has the country, entity and name in cells A2, B2 and C2. I asked ChatGPT for a VBA script for the consolidated.xlsm workbook that reads those three cells from every Excel file in the “input” folder next to the workbook and writes them to columns A to C, with the source file name in column D.
Sub ExtractData()
Dim wb As Workbook, ws As Worksheet, wsData As Worksheet
Dim f As String, fPath As String, fname As String
Dim lRow As Long, i As Long
Set wsData = ThisWorkbook.Sheets("Data")
lRow = wsData.Cells(wsData.Rows.Count, "A").End(xlUp).Row
fPath = ThisWorkbook.Path & "\input\"
f = Dir(fPath & "*.xl*")
i = lRow + 1
Do While f <> ""
Set wb = Workbooks.Open(fPath & f)
Set ws = wb.Sheets("Settings")
fname = wb.Name
wsData.Cells(i, "A").Value = ws.Cells(2, "A").Value
wsData.Cells(i, "B").Value = ws.Cells(2, "B").Value
wsData.Cells(i, "C").Value = ws.Cells(2, "C").Value
wsData.Cells(i, "D").Value = fname
wb.Close False
f = Dir()
i = i + 1
Loop
MsgBox "Data extraction completed."
End Sub
I pasted the code into a module, compiled it and ran it. Excel opened each file in turn and wrote one row per file. The code has no error handling and opens every file visibly, so it is a starting point rather than a finished tool. The same consolidation job in Python is in copying data from multiple Excel files into a master file.
Send personalized emails
The second macro drafts one Outlook email per row of a table, with a personalized subject and body and a file attached. It needed a few fixes before it ran.
The workbook has an attachments folder next to it and a table named “tbl_EMAIL_LIST” on the “distribution_list” sheet, with columns for the receiver, the CC address, the recipient name and the attachment file name. The subject and body are named cells with {NAME} and {ATTACHMENT} placeholders. I asked ChatGPT to loop through the table, fill in the placeholders and attach the file.
The first version referred to the wrong columns and was missing the Outlook library. Below is the final version from the GitHub repository. It declares Outlook types, so set a reference to the Microsoft Outlook Object Library under Tools, References in the VBA editor first.
Sub SendEmails()
Dim outlookApp As Outlook.Application
Dim outlookMail As Outlook.MailItem
Dim rng As Range
Dim row As Long
Dim recipient As String
Dim cc As String
Dim name As String
Dim attachment As String
Dim body As String
Dim subject As String
Set outlookApp = CreateObject("Outlook.Application")
Set rng = ThisWorkbook.Worksheets("distribution_list").ListObjects("tbl_EMAIL_LIST").Range
For row = 2 To rng.Rows.Count
recipient = rng.Cells(row, 1).Value
cc = rng.Cells(row, 2).Value
name = rng.Cells(row, 3).Value
attachment = rng.Cells(row, 4).Value
Set outlookMail = outlookApp.CreateItem(olMailItem)
With outlookMail
.To = recipient
.cc = cc
.subject = Replace(ThisWorkbook.Names("SUBJECT").RefersToRange.Value, "{NAME}", name)
body = Replace(ThisWorkbook.Names("BODY").RefersToRange.Value, "{NAME}", name)
body = Replace(body, "{ATTACHMENT}", attachment)
.body = body
.Attachments.Add ThisWorkbook.Path & "\attachments\" & attachment
.Display
End With
Next row
End Sub
After those fixes it created draft emails with the right recipients, subjects, attachments and body text. .Display opens each draft for review; change it to .Send only once you trust the output. If you would rather not maintain a macro, there is also a Windows app that sends emails from your Excel list.
Find and replace across files
The third macro replaces text in every workbook of an input folder and saves the changed copies to an Output folder, which it creates if needed. The first version did not compile.
I wanted “Small Business” replaced with “Small Market” and “Midmarket” with “Midsize Market”. ChatGPT’s code used two folder path variables without declaring them, which Option Explicit rejects. After I declared and set both paths, it ran and created the output folder with the changed files.
Option Explicit
Sub ReplaceTextInExcelFiles()
' Declare variables
Dim fso As Object, inputFolder As Object, file As Object
Dim wb As Workbook, ws As Worksheet
Dim outputFolder As String
Dim findText As String, replaceText As String
Dim inputFolderPath As String
Dim outputFolderPath As String
' Set input and output folder paths
inputFolderPath = ThisWorkbook.Path & "\Input\"
outputFolderPath = ThisWorkbook.Path & "\Output\"
' Create the output folder if it doesn't exist
If Not FolderExists(outputFolderPath) Then
MkDir outputFolderPath
End If
' Create a FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
' Get the input folder
Set inputFolder = fso.GetFolder(inputFolderPath)
' Iterate through all files in the input folder
For Each file In inputFolder.Files
' Check if the file is an Excel file
If LCase(Right(file.Name, 4)) = ".xls" Or LCase(Right(file.Name, 5)) = ".xlsx" Then
' Open the Excel file
Set wb = Workbooks.Open(file.Path)
' Iterate through all sheets in the workbook
For Each ws In wb.Sheets
' Replace instances of 'Small Business' with 'Small Market'
findText = "Small Business"
replaceText = "Small Market"
ws.Cells.Replace findText, replaceText, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False
' Replace instances of 'Midmarket' with 'Midsize Market'
findText = "Midmarket"
replaceText = "Midsize Market"
ws.Cells.Replace findText, replaceText, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False
Next ws
' Save the modified workbook in the output folder
wb.SaveAs outputFolderPath & file.Name
' Close the workbook
wb.Close
End If
Next file
MsgBox "Text replacement completed!"
End Sub
' Function to check if a folder exists
Function FolderExists(folderPath As String) As Boolean
FolderExists = (Dir(folderPath, vbDirectory) <> "")
End Function
When generated code stops with an error like this, stepping through it line by line finds the culprit fast; my VBA debugging tip shows how.
Pivot table and chart
The last macro builds a pivot table of sales by product on a new “Analysis” sheet and adds a column chart. It took two rounds of fixes.
The first version failed on a grouping property. Once I fixed that, the pivot table was missing columns, because the data range was too narrow. Setting the range to all data columns (A:P) gave a complete pivot table and chart.
Sub GroupAndChart()
'Declare variables
Dim wsData As Worksheet
Dim wsAnalysis As Worksheet
Dim rngData As Range
Dim pvtProductSales As PivotTable
Dim chtProductSales As Chart
'Set worksheet variables
Set wsData = ThisWorkbook.Worksheets("Data")
Set wsAnalysis = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
wsAnalysis.Name = "Analysis"
'Set data range
Set rngData = wsData.Range("A:P")
'Create pivot table
Set pvtProductSales = wsAnalysis.PivotTableWizard(SourceType:=xlDatabase, SourceData:=rngData, TableDestination:=wsAnalysis.Range("A1"), TableName:="PivotTableProductSales")
'Group the data by product
pvtProductSales.PivotFields("Product").Orientation = xlRowField
pvtProductSales.PivotFields("Product").Position = 1
'Summarize the sales data
pvtProductSales.PivotFields("Sales").Orientation = xlDataField
'Create pivot chart
Set chtProductSales = wsAnalysis.Shapes.AddChart2(251, xlColumnClustered, pvtProductSales.TableRange1).Chart
chtProductSales.SetSourceData Source:=pvtProductSales.TableRange1
End Sub
The macro fails if a sheet named “Analysis” already exists, so delete it before running the code again. I ran a similar test with Python instead of VBA in Excel automation with ChatGPT and Python.
