excel 如何重命名表中的每一列?

42fyovps  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(361)

所以我有一个有X列的表,我想用自己的名字重命名每一列。
我想使用A1上的字符串重命名第一列,使用B1上的字符串重命名第二列,依此类推。

我尝试使用:ActiveWorkbook.Names.Add Name:=Name, RefersToR1C1:="=Sheet1!R2C1:R70C1"
但是我想把R2C1:R70C1替换成类似R2CA:R70CA的东西,其中A的值在每一列上都增加,并且用ActiveSheet.Name替换Sheet1
有什么建议吗?
注意:不,表不是对象,所以ActiveWorkbook.Sheets("Sheet").ListObjects("Table").ListColumns("Column name").Name = "New column name"不起作用。
注2:我使用Excel 2013

kuarbcqp

kuarbcqp1#

为每列添加名称

Sub AddNames()
    
    Const FirstCol As String = "A"
    Const FirstRow As Long = 2
    Const LastRow As Long = 70
    
    With ActiveSheet

        Dim wsName As String: wsName = .Name

        Dim fCell As Range: Set fCell = .Cells(FirstRow, FirstCol)
        Dim rg As Range
        Set rg = .Range(fCell, .Cells(FirstRow, .Columns.Count).End(xlToLeft)) _
            .Resize(LastRow - FirstRow + 1)

        Dim crg As Range, ErrNumber As Long, nmName As String

        For Each crg In rg.Columns

            nmName = CStr(crg.Cells(1).Value)

            On Error Resume Next
                .Names.Add nmName, "'" & wsName & "'!" & crg.Address
                ErrNumber = Err.Number
            On Error GoTo 0

            If ErrNumber <> 0 Then
                MsgBox "Could not add name """ & nmName & """.", vbCritical
                ErrNumber = 0
            End If

        Next crg

    End With
        
    MsgBox "Names added.", vbInformation

End Sub
  • 如果只需要数据的范围(没有标题),请使用以下命令:
Sub AddNamesData()
    
    Const FirstCol As String = "A"
    Const FirstRow As Long = 2
    Const LastRow As Long = 70
    
    With ActiveSheet
        
        Dim wsName As String: wsName = .Name
        
        Dim fCell As Range: Set fCell = .Cells(FirstRow, FirstCol)
        Dim rg As Range
        Set rg = .Range(fCell, .Cells(FirstRow, .Columns.Count).End(xlToLeft)) _
            .Resize(LastRow - FirstRow + 1)
        
        Dim hrg As Range: Set hrg = rg.Rows(1)
        Dim drg As Range: Set drg = rg.Resize(rg.Rows.Count - 1).Offset(1)
        
        Dim hCell As Range, c As Long, ErrNumber As Long, nmName As String
        
        For Each hCell In hrg.Cells
            
            c = c + 1
            nmName = CStr(hCell.Value)
            
            On Error Resume Next
                .Names.Add nmName, "'" & wsName & "'!" & drg.Columns(c).Address
                ErrNumber = Err.Number
            On Error GoTo 0
            
            If ErrNumber <> 0 Then
                MsgBox "Could not add name """ & nmName & """.", vbCritical
                ErrNumber = 0
            End If
        
        Next hCell
    
    End With
        
    MsgBox "Names added.", vbInformation

End Sub

相关问题