在Excel中重命名列标题

时间:2017-07-27 09:08:10

标签: excel excel-vba vba

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

  • 单元ID
  • 单位名称

几次

我希望根据它们的出现次数更改这些列标题 例如。第一次出现Unit ID将被替换为Unit ID_1,第二次出现将被重命名为Unit ID_2,依此类推。
任何帮助都将是fab!

3 个答案:

答案 0 :(得分:1)

你有这个标题,对吗?声明一些整数变量: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

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分:0)

对此有答案,下面是代码-

    Dim wbCurrent As Workbook
    Dim wsCurrent As Worksheet
    Dim nLastCol, i, j, k As Integer
    Set wbCurrent = ActiveWorkbook
    Set wsCurrent = wbCurrent.ActiveSheet
    nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    j = 0
For i = nLastCol To 1 Step -1
    j = j + 1
   ' k = InStr(1, wsCurrent.Cells(1, i).Value, "Sweep TID", vbTextCompare) > 0
        If InStr(1, wsCurrent.Cells(1, i).Value, "unitid", vbTextCompare) = 0 Then
            wsCurrent.Cells(1, i).Value = "unitid_" & j
        End If
        If InStr(1, wsCurrent.Cells(1, i).Value, "UnitName", vbTextCompare) > 0 _
        Then
            wsCurrent.Cells(1, i).Value = "UnitName_" & j
        End If
    Next i

上面的代码标识了其中包含数据的最后一列,并在循环中使用