I’m running this code in VBA and I can’t figure out where my error is. I keep getting the error message
“Run-time error ‘438’: Object doesn’t support this property or method”.
I’ve searched the internet for solutions but haven’t been able to find anything that fixed my problem.
Sub FinalCleanUp() Dim wkbk As Workbook Dim wksht As Worksheet Dim DataSheet As Worksheet Dim sheetName As String sheetName = "Data" Set wkbk = ActiveWorkbook 'Delete consolidated data sheet if it already exists For Each wksht In wkbk.Sheets If wksht.Name = sheetName Then wkbk.Sheets(sheetName).Delete Exit For End If Next wksht 'Create new sheet for consolidated data wkbk.Sheets.Add Before:=wkbk.Sheets(1) Set DataSheet = ActiveSheet ActiveSheet.Name = sheetName 'Step through each sheet and copy data to consolidated data sheet 'ERROR IS SOMEWHERE BELOW HERE For Each wksht In wkbk.Sheets If wksht.Name <> sheetName Then wksht.Activate Range(Cells(1, 1), Cells(ActiveSheet.UsedRange.Rows.Count, ActiveSheet.UsedRange.Columns.Count)).Copy If wksht = wkbk.Sheets(2) Then DataSheet.Activate Cells(ActiveSheet.UsedRange.Rows.Count, 1).Select Else DataSheet.Activate Cells(ActiveSheet.UsedRange.Rows.Count + 1, 1).Select End If ActiveSheet.Paste End If Next wksht End Sub
This code is supposed to take data from multiple worksheets and consolidate it into one worksheet. As previously stated, I get a run-time error and no output when I run the macro.
The error is here:
If wksht = wkbk.Sheets(2) Then
Worksheet class doesn’t have a default property, so you can’t let-coerce that object; VBA is trying to invoke the default member of
Worksheet to satisfy the comparison operator, but there’s no such member, so error 438 is raised.
I think what you’re trying to do is to validate whether
wkbk.Sheets(2). You need the
Is operator for reference equality:
If wksht Is wkbk.Sheets(2) Then
Note that this is different from comparing the
.Name of the sheets: here we’re comparing object references.
That said, I’d buy a vowel or two here, it’s too easy to make a typo typing those… Make sure
Option Explicit is specified!
wkbk.Sheets.Add Before:=wkbk.Sheets(1) Set DataSheet = ActiveSheet
Worksheets.Add returns the added worksheet object, so you can do this instead, and not rely on the side-effect of the added sheet now being the
Set DataSheet = wkbk.Sheets.Add(Before:=wkbk.Sheets(1))