Rename duplicate column header names

abenitez77

Board Regular
Joined
Dec 30, 2004
Messages
149
I have a spreadsheet that gets created dynamically..and has x number of columns. It has column header names and sometimes these could contain duplicates. I want to rename one by putting a "2" at the end of the column header so that there are no duplicates. How can i do this with vba?

I tried code to help me get close but does not work...It errors out in the If Application... row

'Rename any Duplicate Column names
With Sheets(myCurrentSheet)
For thisCol = lastCol To 2 Step -1
If Application.Match(.Cells(1, thisCol).Value, Range(.Cells(1, 1), .Cells(1, lastCol)), 0) <> thisCol Then
' If Application.Match(.Cells(1, thisCol).Value, .Range("1:1"), 0) < thisCol Then

MsgBox ("Duplicate")
End If
Next thisCol
End With
 

Excel Facts

How to change case of text in Excel?
Use =UPPER() for upper case, =LOWER() for lower case, and =PROPER() for proper case. PROPER won't capitalize second c in Mccartney
This seems to work. It will work with multiple duplicates, so it will keep count of how many duplicates it has found and add a "2", "3", "4", etc,.

Code:
Sub DuplicateColumns()
Dim r As Range:         Set r = Range("A1:H1") 'Change to area where your column headers are.
Dim AR() As Variant:    AR = r.Value
Dim SD As Object:       Set SD = CreateObject("Scripting.Dictionary")


For i = LBound(AR) To UBound(AR, 2)
    If SD.exists(AR(1, i)) Then
        SD(AR(1, i)) = SD(AR(1, i)) + 1
        AR(1, i) = AR(1, i) & SD(AR(1, i))
    Else
        SD(AR(1, i)) = 1
    End If
Next i


r.Value = AR
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,639
Messages
6,173,499
Members
452,517
Latest member
SoerenB

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top