将If语句与Vlookup结合

时间:2018-07-16 08:11:17

标签: excel excel-vba if-statement excel-formula vlookup

我正在尝试将一个带有If条件的vlookup公式合并。更确切地说,我有一个工作表,如果E AND 列的单元格为0,我希望在G列的单元格中执行vlookup公式。变量 lastrow3 ws1 已正确定义并具有适当的值。另外,我已经运行了没有if条件的代码(仅是vlookup),并且运行得很好。因此,这些变量不可能出现问题。此外,我希望 vlookup是动态的 。我已经编写了4种不同类型的代码。我在下面提供它们。

CODE1

For i = 2 To lastrow3
ws1.Range("G" & i).Formula = "=IF(E" & i & "+ F" & i & " = 0, " & Chr(34) & "VLOOKUP(C"&i&",'[NOT OK.xlsx]Sheet1'!F:I,4,FALSE)" & Chr(34) & ", " & Chr(34) & "No" & Chr(34) & ")"
Next i

这段代码在这一部分给了我一个错误:"VLOOKUP(C"&i&",说出语法错误。

CODE2

For Each cell In ws1.Range("G2:G" & lastrow3)
    If cell.Offset(0, -1).Value = 0 Then
        If cell.Offset(0, -2).Value = 0 Then
        cell.Formula = "=IFERROR(VLOOKUP(C2,'[NOT OK.xlsx]Sheet1'!F:I,4,FALSE),"""")"
        End If
    End If
Next cell

此代码在此部分给出了错误:If cell.Offset(0, -1).Value = 0 Then表示存在类型不匹配。另外,此代码没有动态vlookup,因此仅对单元格C2进行vlookups。

CODE3

With ws1
   For i = 2 To lastrow3
       If .Cells(i, "E").Value2 = 0 And .Cells(i, "F").Value2 = 0 Then
       .Cells(i, "G").Formula = "=IFERROR(VLOOKUP($C$" & i&",'[NOT OK.xlsx]Sheet1'!F:I,4,FALSE),"""")"
       End If
   Next cell
End With

这段代码给我这部分错误:.Cells(i, "G").Formula = "=IFERROR(VLOOKUP($C$" & i&",'[NOT OK.xlsx]Sheet1'!F:I,4,FALSE),"""")"说存在语法错误。

CODE4

With ws1
    .Range("G2:G" & lastrow3).Formula = "=IFERROR(VLOOKUP(C2,'[NOT OK.xlsx]Sheet1'!F:I,4,FALSE),"""")"
    .Range("G2:G" & lastrow3).Value = .Range("G2:G" & lastrow3).Value
End With

此代码运行正常(这是我运行并验证变量定义正确的代码)位不包含If条件。 我想声明这段代码运行的非常快(使用With ws1和End With),因此,如果可以通过添加if条件使这段代码运行,那将是完美的。

CODE5(->我试图在CODE4中添加If条件)

With ws1
If  .Range("G2:G" & lastrow3).Offset(0, -1).Value = 0 And .Range("G2:G" & lastrow3).Offset(0, -2).Value = 0 Then
    .Range("G2:G" & lastrow3).Formula = "=IFERROR(VLOOKUP(C2,'[NOT OK.xlsx]Sheet1'!F:I,4,FALSE),"""")"
End If
    .Range("G2:G" & lastrow3).Value = .Range("G2:G" & lastrow3).Value
End With

这段代码给我这部分错误:If .Range("G2:G" & lastrow3).Offset(0, -1).Value = 0 And .Range("G2:G" & lastrow3).Offset(0, -2).Value = 0 Then说类型不匹配。

摘要

我正在尝试在代码中结合速度和准确性。根据我的搜索,带有With和End With的代码是最快的。但是,如果我设法用其他代码解决它,那么就没有问题。我遇到的主要错误是在vlookup公式中,当我尝试使其动态化时,在if条件中,当我尝试查找偏移量是否具有0值时。

到目前为止,我正在添加整个代码(尽管我认为这并不重要)

完整代码

Sub Pharma_Stock_Report()



Dim StartTime As Double
Dim SecondsElapsed As Double
StartTime = Timer



Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False

Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim lastrow1 As Long
Dim lastrow2 As Long
Dim lastrow3 As Long
Dim CopyRange As Range
Dim i As Long

spath1 = Application.ThisWorkbook.Path & "\Pharma replenishment.xlsm"
spath2 = Application.ThisWorkbook.Path & "\NOT OK.xlsx"
Workbooks.Open spath1
Workbooks.Open spath2

Set ws1 = Workbooks("Pharma Stock Report.xlsm").Worksheets("Pharma Stock Report")
Set ws2 = Workbooks("Pharma replenishment.xlsm").Worksheets("Replenishment")
Set ws3 = Workbooks("NOT OK.xlsx").Worksheets("Sheet1")

With ws1
    .Cells.Clear
End With

With ws2
lastrow1 = .Range("A" & Rows.Count).End(xlUp).Row
    For i = 4 To lastrow1
        If .Cells(i, "D").Interior.ColorIndex = -4142 Or .Cells(i, "D").Interior.ColorIndex = 2 Then
            If CopyRange Is Nothing Then
                Set CopyRange = .Range("A" & i & ":F" & i)
            Else
                Set CopyRange = Union(CopyRange, .Range("A" & i & ":F" & i))
            End If
        End If
    Next i
End With

CopyRange.Copy
With ws1.Range("A2")
    .PasteSpecial xlPasteValues
End With

ws2.Range("A4:F4").Copy
With ws1.Range("A1")
    .PasteSpecial xlPasteValues
End With

Application.CutCopyMode = False
Workbooks("Pharma replenishment.xlsm").Close

ws3.Range("I1").Copy
With ws1.Range("G1")
    .PasteSpecial xlPasteValues
End With

lastrow3 = ws1.Range("D" & Rows.Count).End(xlUp).Row

With ws1
    .Range("G2:G" & lastrow3).Formula = "=IFERROR(VLOOKUP(C2,'[NOT OK.xlsx]Sheet1'!F:I,4,FALSE),"""")"
    .Range("G2:G" & lastrow3).Value = .Range("G2:G" & lastrow3).Value
End With

Application.CutCopyMode = False
Workbooks("NOT OK.xlsx").Close

With ws1.Range("A1:G" & lastrow3)
    .HorizontalAlignment = xlCenter
    .Font.Color = vbBlack
    .Font.Name = "Calibri"
    .Font.Italic = False
    .Borders.LineStyle = xlDouble
    .Borders.Weight = xlThin
    .Borders.Color = vbBlack
End With

With ws1.Range("A1:G1")
    .Interior.ColorIndex = 41
    .Font.Bold = True
    .Font.Size = 14
    .Font.Italic = True
End With

With ws1.Range("A1", Range("A1").End(xlDown).End(xlToRight))
    .EntireColumn.AutoFit
End With

ws1.Range("A1:G1").AutoFilter
ws1.AutoFilter.Sort.SortFields.Add Key:=Range("B1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ws1.AutoFilter.Sort
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True



SecondsElapsed = Round(Timer - StartTime, 2)
MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation



End Sub

3 个答案:

答案 0 :(得分:1)

第一个代码很容易解决:实际上存在语法错误,因为vba在变量名和&-运算符之间需要空格。添加空格

ws1.Range("G" & i).Formula = "=IF(E" & i & "+ F" & i & " = 0, " & Chr(34) & "VLOOKUP(C" & i & ",'[NOT OK.xlsx]Sheet1'!F:I,4,FALSE)" & Chr(34) & ", " & Chr(34) & "No" & Chr(34) & ")"

将解决该问题。

答案 1 :(得分:1)

CODE1有一些问题。您已在Chr(34)周围插入了VLOOKUP,除非您希望单元格显示查找​​公式,而不是查找的 result ,否则它们需要继续。 / p>

ws1.Range("G" & i).Formula = "=IF(E" & i & "+ F" & i & " = 0, " & "VLOOKUP(C" & i & ",'[NOT OK.xlsx]Sheet1'!F:I,4,FALSE)" & ", " & Chr(34) & "No" & Chr(34) & ")"

要清除零和#N/A-

ws1.Range("G" & i).Formula = "=IFNA(IF(E" & i & "+ F" & i & " = 0, " & "IF(IFNA(VLOOKUP(C" & i & ",'[NOT OK.xlsx]Sheet1'!F:I,4,FALSE),0)=0,"""",IFNA(VLOOKUP(C" & i & ",'[NOT OK.xlsx]Sheet1'!F:I,4,FALSE),0))" & ", " & Chr(34) & "No" & Chr(34) & "),"""")"

答案 2 :(得分:0)

您当前的代码正在测试一系列值,这很可能就是您遇到类型问题的原因

相反,在公式中添加if测试会更容易(然后使用R1C1表示法创建引用的查询)

.Range("G2:G" & lastrow3).FormulaR1C1 = "=IF(AND(RC[-2]=0,RC[-1]=0),IFERROR(VLOOKUP(RC[-4],'[NOT OK.xlsx]Sheet1'!C[-1]:C[2],4,FALSE),""""),"Null Values")"