多步骤VLookup,替代,然后评估过程

时间:2013-10-23 13:29:43

标签: excel-vba vba excel

我有一个三步过程,它应该最终给出我的布尔值True / False,偶尔还有#N / A或#VALUE(我实际上想要保留为错误)。我正在使用具有多个命名工作表的工作簿,并通过VLookup从一个选项卡中提取单元格值,替换这些值中的字符串,然后将这些值转换为要评估的公式。这是我到目前为止所拥有的;我在代码中包含了注释,解释了我遇到的问题。

Public Sub DetermineRowsToExamine()

'Define what our Rows are for the calculations
    Dim NumRecords As Long
    NumRecords = Workbooks("POVA Daily Reporter.xlsm").Worksheets("Paste Daily Data").Range("B" & Rows.Count).End(xlUp).Row
    Dim CellsForFormula As Range
    Set CellsForFormula = Workbooks("POVA Daily Reporter.xlsm").Worksheets("Paste Daily Data").Range("g2", "G" & NumRecords)


'Now I Insert the VLookup
    Dim WSLogic As Worksheet
    Dim WSData As Worksheet
    Set WSData = Workbooks("POVA Daily Reporter.xlsm").Worksheets("Paste Daily Data")
    Set WSLogic = Workbooks("POVA Daily Reporter.xlsm").Worksheets("Logic Statements")

    CellsForFormula.Value = Application.WorksheetFunction.VLookup(WSData.Range("B2"), WSLogic.Range("A:D"), 4, False)

'This works in principle, but the problem is the "B2" in the VLookup - I need the "B2" to change to "B3" related
'to each row, just as it would if I pasted the rows down the columns as an cell formula

'Now I want to take that value and perform a replacement:
    CellsForFormula.Value = Application.WorksheetFunction.Substitute(Range("g2"), "ZZZ", "C2")

'Again, this works great, but I need it to replace "G2" or "G3" or whatever cell it's in.

'Finally, I then want to evaluate that cell as if it were a formula. When the above calculations are working,
'I end up with:  AND(LEN(C2)=10,OR(LEFT(C2,2)="57",LEFT(C2,2)="13"))
'I want to evaluate this as a formula, basically making it =AND(LEN(C2)=10,OR(LEFT(C2,2)="57",LEFT(C2,2)="13"))


End Sub

我认为我不理解的是如何让VLookup和Substitute函数中的Cell引用与我所在的行相关。

1 个答案:

答案 0 :(得分:0)

同意@AlanWaage所说的内容,您应该将实际的VLOOKUP公式放在单元格中。然后,要使公式相对于其位置进行更新,您可以使用复制和粘贴。最后,在那里有公式后,您可以复制并粘贴值,并根据CellsForFormula范围内的值进行替换。请参阅下面的更新代码:

' Put the formula in the first cell of your range
CellsForFormula(1, 1).Formula = _
    "=VLOOKUP(Paste Daily Data!B2,Logic Statements!$A$1:$D$10000,4,0)"

' Copy the formula to the rest of your range
CellsForFormula(1, 1).Copy _
    Destination:=Range(CellsForFormula(2, 1), CellsForFormula(NumRecords - 1, 1))

' Copy and paste values to just get the values in your range
CellsForFormula.Copy
CellsForFormula.PasteSpecial Paste:=xlPasteValues

' Execute your replacement
for each cell in CellsForFormula
    cell.Replace("ZZZ", cell.offset(0,-4).Address)
    'Use the line below instead of the line above if you only
    'want to replace if the entire value is "ZZZ"
    'cell.Replace("ZZZ", cell.offset(0,-4).Address,xlWhole)
    cell.Formula = "=" & cell.value
Next cell

<强> --- --- EDIT

请注意,我执行了Logic Statements!$A$1:$D$10000而不是Logic Statements!A:D;这比Excel检查A:D列中的所有行要快得多。根据需要将此数字设置为更大或更小,但除非必要,否则应尽量避免在公式中使用完整的列/行引用