使用 Excel VBA 搜索列标题并插入新列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42439988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 12:11:31  来源:igfitidea点击:

Search column headers and insert new column using Excel VBA

excelexcel-vbavba

提问by Graham McCubbin

I have a spreadsheet that is updated regularly. Therefore the column header positions change regularly. eg. today "Username" is column K, but tomorrow "Username" might be column L. I need to add a new column to the right of "Username" but where it changes I cannot refer to as cell/column reference.

我有一个定期更新的电子表格。因此,列标题位置会定期更改。例如。今天“用户名”是 K 列,但明天“用户名”可能是 L 列。我需要在“用户名”右侧添加一个新列,但它发生变化的地方我不能将其称为单元格/列引用。

So far I have:

到目前为止,我有:

Dim rngUsernameHeader As Range
Dim rngHeaders As Range
Set rngHeaders = Range("1:1") 'Looks in entire first row.
Set rngUsernameHeader = rngHeaders.Find("Username")

When I go to add a new column to the right of it, I'm selecting that row but it's going back to cell/column references...

当我在它的右侧添加一个新列时,我选择了该行,但它又回到了单元格/列引用......

Columns("K:K").Select
Selection.Insert Shift:=xlToRight
Range("K1").Select
ActiveCell.FormulaR1C1 = "Role"

How can I perform this step with a macro?

如何使用宏执行此步骤?

edit:I think need to give that Column a header name and begin populating the row with data - each time I do begins the cell references which I want to avoid wherever possible.

编辑:我认为需要给该列一个标题名称并开始用数据填充该行 - 每次我开始我想尽可能避免的单元格引用。

Many thanks in advance.

提前谢谢了。

采纳答案by Gary's Student

How about:

怎么样:

Sub qwerty()
    Dim rngUsernameHeader As Range
    Dim rngHeaders As Range

    Set rngHeaders = Range("1:1") 'Looks in entire first row.
    Set rngUsernameHeader = rngHeaders.Find(what:="Username", After:=Cells(1, 1))

    rngUsernameHeader.Offset(0, 1).EntireColumn.Insert
    rngUsernameHeader.Offset(0, 1).Value = "role"
End Sub

回答by Alex P

Sub AddColumn
    Dim cl as Range

    For each cl in Range("1:1")
        If cl = "username" Then
           cl.EntireColumn.Insert Shift:= xlToRight
        End If

        cl.Offset(0, 1) = "role"
    Next cl
End Sub

Untested code as not at my desktop

未经测试的代码不在我的桌面上

回答by Darren Bartrup-Cook

You could name your range:

你可以命名你的范围:

Sub Test()

    Dim rngUsernameHeader As Range
    'UserName is in column F at the moment.
    Set rngUsernameHeader = Range("UserName")
    Debug.Print rngUsernameHeader.Address 'Returns $F
    ThisWorkbook.Worksheets("Sheet2").Range("E:E").Insert Shift:=xlToRight
    Debug.Print rngUsernameHeader.Address 'Returns $G

End Sub

Edit:Have rewritten so it inserts a column after your named column and returns that reference:

编辑:已重写,因此它会在您命名的列之后插入一列并返回该引用:

Sub Test()

    Dim rngUsernameHeader As Range
    Dim rngMyNewColumn As Range

    Set rngUsernameHeader = Range("UserName")
    rngUsernameHeader.Offset(, 1).Insert Shift:=xlToRight

    'You'll need to check the named range doesn't exist first.
    ThisWorkbook.Names.Add Name:="MyNewRange", _
        RefersTo:="='" & rngUsernameHeader.Parent.Name & "'!" & _
                         rngUsernameHeader.Offset(, 1).Address

    Set rngMyNewColumn = Range("MyNewRange")
    MsgBox rngMyNewColumn.Address

End Sub

回答by Vityata

Something like this should work. The idea is that you locate the column and then you insert to the right. That is why you have the +1in the TestMe. The function l_locate_value_colreturns the column, where it has found the value. If you want, you may change the optional parameter l_row, depending on which row do you want to look for.

像这样的事情应该有效。这个想法是您找到该列,然后向右插入。这就是为什么你+1TestMe. 该函数l_locate_value_col返回找到该值的列。如果需要,您可以更改可选参数l_row,具体取决于您要查找的行。

Option Explicit

Public Sub TestMe()

    Dim lngColumn         As Long

    lngColumn = l_locate_value_col("Username", ActiveSheet)
    Cells(1, lngColumn + 1).EntireColumn.Insert

End Sub

Public Function l_locate_value_col(target As String, _
                                    ByRef target_sheet As Worksheet, _
                                    Optional l_row As Long = 1)

    Dim cell_to_find                As Range
    Dim r_local_range               As Range
    Dim my_cell                     As Range

    Set r_local_range = target_sheet.Range(target_sheet.Cells(l_row, 1), target_sheet.Cells(l_row, Columns.Count))

    For Each my_cell In r_local_range
        If target = Trim(my_cell) Then
            l_locate_value_col = my_cell.Column
            Exit Function
        End If
    Next my_cell

    l_locate_value_col = -1

End Function