VBA:在一列中查找文本,如果为true,则将其旁边列中的文本与单独的工作表中的列匹配,并插入公式

请随身携带,因为我是VBA的新手! 这是我有:

响应stream程

我有一张名为Response Flow的表,有Response,Y / N和Total。 如果响应在其旁边有一个Y,我希望将响应名称与表2上的响应名称(“Campaigns”)相匹配,并使用VBA代码在Sheet 2的响应名称旁边的列中插入一个公式。 以下是我到目前为止。

Sub Volume_Calc() Dim LastRowR As Long Dim LastRowC As Long Dim LastRowI As Long Dim LastRowA As Long Dim rngFoundCell As Range Dim cell As Range Dim text As String Dim FindRow As Range LastRowR = Range("C65536").End(xlUp).Row LastRowC = Range("K65536").End(xlUp).Row LastRowI = Range("I65536").End(xlUp).Row LastRowA = Range("A65536").End(xlUp).Row Set FindRow = Worksheets("ResponseFlow").Range("C:C").Find(What:="Y", LookIn:=xlValues) Do While FindRow = True If Application.Match(Worksheets("Campaigns").Range("K6"), Worksheets("ResponseFlow").Range("A4:A" & LastRowA), 0) Then Worksheets("Campaigns").Range("I6:I" & LastRowI).Formula = "=INDEX(ResponseFlow!$B$3:$B$145,MATCH(Campaigns!$K6,ResponseFlow!$A$3:$A$145,0))" End If Loop End Sub 

你打算做什么似乎在不使用VBA的Excel中更容易做到,但是如果你坚持使用一些macros插入公式,这可能是一个简单的方法。 首先把你想要粘贴的dynamic公式放在表格右边的Y / N,SOMEWHERE列的右边。 在我的例子中,我使用了Cell(“Z1”)。 确保它是dynamic的,这样如果你要复制/粘贴公式到另一个单元格,它会正确调整。

再次确保您所需的任何dynamic匹配公式都适合您的值,并将其configuration为dynamic。 在我的例子中,它在单元格Z1上的响应ws。

 Sub Volume_Calc() Dim Resp_WS As Worksheet: Set Resp_WS = Worksheets("ResponseFlow") Dim CAMP_WS As Worksheet: Set CAMP_WS = Worksheets("Campaigns") Dim rCell As Range Dim cCell As Range 'Loops through Response Sheeet column "C" looking for values of "Y" For Each rCell In Intersect(Resp_WS.Range("C:C"), WResp_WS.UsedRange).Cells If UCase(rCell.Value) = "Y" Then 'When finds a cell with Y, it then loops through Campaigns Sheet column "I" 'looking for a value that matches one column to the left where the "Y" was found For Each cCell In Intersect(CAMP_WS.UsedRange, CAMP_WS.Range("I:I")).Cells 'When match is found, the macro will insert the formula to the right 'of the cell in Campaigns, with the dynamically updated formula in cell Z1 If cCell.Value = rCell.offset(0,-1).Value Then cCell.Offset(0, 1).FormulaR1C1 = Resp_WS.Range("Z1").FormulaR1C1 End If Next cCell End If Next rCell End Sub