BACKGROUND
I've created a VBA macro to pull in financial data from various business units.
OBJECTIVE
After consolidating each business unit's financial information, insert a row with column headers to prepare for a pivot table report.
APPROACH
- Define worksheet
- Define "header" array
- Insert 1 row at top of excel sheet, shift all other rows down by 1
- Insert header array text values into columns
CODE BASE
Sub addHeaders()
Dim ws As Worksheet
Dim headers() As Variant
'Define worksheet and desired headers
Set ws = ThisWorkbook.Sheets("CONSOLIDATED")
headers() = Array("Fiscal Year", "Month", "Month_Year", "Project", "Local Expense", "Base Expense")
'Insert row for header placement
Rows(1).Insert shift:=xlShiftDown
'Insert headers
With ws
For i = LBound(headers()) To UBound(headers())
.Cells(1, 1 + i).Value = headers(i)
Next i
End With
End Sub
ISSUE(S)
- "Object variable or With block variable are not set" @ line
.Cells(1, 1 + i).Value = headers(i)
QUESTION
- Why is VBA saying that the variable (assuming "ws") was not set when I've clearly defined
Set ws = ThisWorkbook.Sheets("CONSOLIDATED")
ThisWorkbookand notActiveWorkbook?