在Excel中重命名列标题

我有相同的列在工作表中重复,如

  • 单位ID
  • 单位名称

几次

我希望这些列标题根据其发生情况进行更改。
例如。 第一次出现的Unit ID将被replace为Unit ID_1 ,第二次出现将被重新命名为Unit ID_2等等。
任何帮助将是fab!

你有这个标题在一排,对不对? 声明一些整型variables: Dim i As Integer并将其设置为1 i = 1 ,在循环中遍历该行,每次遇到指定的标题时,都递增i并将其追加到名称:

 If Cells(1, j).Value = "Unit ID" Then 'assumed that first row contains headers and j is loop variable Cells(1, j).Value = Cells(1, j).Value & "_" & i i = i + 1 End If 

尝试这个:

 Option Explicit Sub Demo() Dim lastCol As Long, idCount As Long, nameCount As Long, headerRow As Long Dim rng As Range, cel As Range headerRow = 1 'row number with headers lastCol = Cells(headerRow, Columns.Count).End(xlToLeft).Column 'last column in header row idCount = 1 nameCount = 1 Set rng = Sheets("Sheet1").Range(Cells(headerRow, 1), Cells(headerRow, lastCol)) 'header range For Each cel In rng 'loop through each cell in header If cel = "Unit ID" Then 'check if header is "Unit ID" cel = "Unit ID_" & idCount 'rename "Unit ID" using idCount idCount = idCount + 1 'increment idCount ElseIf cel = "Unit Name" Then 'check if header is "Unit Name" cel = "Unit Name_" & nameCount 'rename "Unit Name" using nameCount nameCount = nameCount + 1 'increment nameCount End If Next cel End Sub