VBA在公式中按名称和参考值查找列

我是新来的vba,我只知道我不得不使用(不多),我已经尝试frankenstein一起复制所有在其他线程中的有用的build议,但我做了一团糟它。

  • 我需要按名称find一列(不会总是在同一个地方)
  • 我需要用引用刚刚find的列的公式填充第一个打开的列(不总是在同一个地方)
  • 如果我可以写一个标题名称,那就是膨胀。

    Sub Labels() Dim NextEmptyCol As Long Dim lastRow As Long SearchV = Range("A1:DD1").Find(What:="team_id", LookIn:=xlValues, LookAt:=xlWhole, _ MatchCase:=False, SearchFormat:=False).Column lastRow = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row NextEmptyCol = Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column + 1 Range(lastRow & Cells(Rows.Count, "A").End(xlUp).Row).Formula = "=b1+c1" End Sub 

    我不知道我在做什么 – 这是从其他论坛主题拼凑而成,但我认为SearchV会find列,lastRow会发现需要填充多less个单元格,NextEmptyCol会把它们放在下一列。 (b1 + c1只是一个占位符公式 – 我不知道如何引用我在第一位find的列。

真是一团糟。

你的问题是你引用一个范围有两行: lastRow & Cells(Rows.Count, "A").End(xlUp).Row 。 我想你想要的Range(NextEmptyCol & lastRow).Formula = "=B1+C1"

如果我find了你想要的东西,你可以在最后一次使用之后去找列,然后用一个公式=[column B] + [column with search term]填充它。 这应该做到这一点:

 Sub DoFomula() Dim SearchV As Long Dim myRange As Range 'column to write in / offset for headers Set myRange = Cells(1, Columns.Count).End(xlToLeft).Offset(1, 1) 'height we need Set myRange = myRange.Resize(Range("B" & Rows.Count).End(xlUp).Row - 1, 1) 'column we do look for SearchV = Application.Match("team_id", Rows(1), 0) 'input formula myRange.FormulaR1C1 = "=RC2 + RC" & SearchV 'your header myRange.Offset(-1).Resize(1).Value = "My New Header" End Sub 

应该是自我解释,但如果你还有任何问题,只要问:)

我相信这可能是你正在寻找的东西:

 Sub subLabels() Dim NextEmptyCol As Long Dim lastRow As Long Dim rngFound As Range 'Change the sheet name in the next line (if necessary) to the correct one With Worksheets("Sheet1") Set rngFound = .Range("A1:DD1").Find(What:="team_id", LookIn:=xlValues, LookAt:=xlWhole, _ MatchCase:=False, SearchFormat:=False) 'Proceed only if "team_id" was found If Not rngFound Is Nothing Then lastRow = .Range("B" & .Rows.Count).End(xlUp).Row NextEmptyCol = .Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column + 1 .Cells(lastRow, NextEmptyCol).Formula = "=B" & lastRow & "+C" & lastRow Else MsgBox "Column 'team_id' not found." & Chr(10) & "Aborting!" End If End With End Sub 

这里是变化:

  1. 如果macros在另一个工作表处于活动状态时运行,我添加了对特定工作表的引用,而不是ActiveSheet 。 否则,这将搞乱你的文件。 您可能必须在那里更改工作表名称。
  2. 在设置公式的行中交换方法Range for Cells
  3. 包括无法find“team_id”列的可能性。
  4. 使配方模块化。 否则,任何一行中的公式都是=B1+C1 。 相反,你可能想要它在第25行=B25+C25 。如果不是这样的话,那么你可以很容易地将其改回。

注意:不要犹豫在代码中标记任何关键字,然后按F1键了解更多信息。 例如:突出显示单词cells ,然后按F1键以了解cellsrange之间的差异。