找到文本并返回其值,如果找不到文本则返回0

时间:2017-03-29 09:42:55

标签: vba excel-vba excel-2010 excel

我需要你的帮助。无法弄清楚为什么下面这段代码不起作用。我有一个数据透视表,我在其中查找具有函数FIND和VLOOKUP的特定值并将其添加到特定单元格:

enter image description here

数据更新后 - 没有关于国家持续时间10-19天的信息。在这种情况下,当某些类别值不存在时 - 我想将0值分配给特定的单元格。 我试着写下以下内容:

Dim x As Long
Dim Lookup_Range, RangeA As range

With Worksheets("Duration")

Set Lookup_Range = Worksheets("Duration").range("A1:B56")

On Error Resume Next
x = Lookup_Range.Find("1 - 9 days", range("A1"), xlValues, xlWhole, xlByColumns, xlNext).Row

Set RangeA = .range(.Cells(x, 1), .Cells(x + 4, 2))

If Not x <> "" Then

   .Cells(30, 7) = Application.VLookup("State1", RangeA, 2, False)
   .Cells(31, 7) = Application.VLookup("State2", RangeA, 2, False)
   .Cells(32, 7) = Application.VLookup("State3", RangeA, 2, False)
   .Cells(33, 7) = Application.VLookup("State4", RangeA, 2, False)

Else

   .Cells(30, 7) = 0
   .Cells(31, 7) = 0
   .Cells(32, 7) = 0
   .Cells(33, 7) = 0

End If

On Error Resume Next
x = Lookup_Range.Find("10 - 19 days", range("A1"), xlValues, xlWhole, xlByColumns, xlNext).Row

Set RangeA = .range(.Cells(x, 1), .Cells(x + 4, 2))

If Not x <> "" Then

   .Cells(34, 7) = Application.VLookup("State1", RangeA, 2, False)
   .Cells(35, 7) = Application.VLookup("State2", RangeA, 2, False)
   .Cells(36, 7) = Application.VLookup("State3", RangeA, 2, False)
   .Cells(37, 7) = Application.VLookup("State4", RangeA, 2, False)

Else

.Cells(34, 7) = 0
.Cells(35, 7) = 0
.Cells(36, 7) = 0
.Cells(37, 7) = 0

End If

End With

只有在满足IF的第一个条件时,它才会返回正确的值。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

这会添加一些检查,找出值,以避免错误。

Sub xy()

Dim x As Long, r As Range

Dim Lookup_Range, RangeA As Range

With Worksheets("Duration")
    Set Lookup_Range = .Range("A1:B56")
    Set r = Lookup_Range.Find("1 - 9 days", .Range("A1"), xlValues, xlWhole, xlByColumns, xlNext)
    If Not r Is Nothing Then
        x = r.Row
        Set RangeA = .Range(.Cells(x, 1), .Cells(x + 4, 2))
        .Cells(30, 7) = Application.VLookup("State1", RangeA, 2, False)
        .Cells(31, 7) = Application.VLookup("State2", RangeA, 2, False)
        .Cells(32, 7) = Application.VLookup("State3", RangeA, 2, False)
        .Cells(33, 7) = Application.VLookup("State4", RangeA, 2, False)
    Else
        .Cells(30, 7) = 0
        .Cells(31, 7) = 0
        .Cells(32, 7) = 0
        .Cells(33, 7) = 0
    End If
    Set r = Lookup_Range.Find("10 - 19 days")
    If Not r Is Nothing Then
        x = r.Row
        Set RangeA = .Range(.Cells(x, 1), .Cells(x + 4, 2))
        .Cells(34, 7) = Application.VLookup("State1", RangeA, 2, False)
        .Cells(35, 7) = Application.VLookup("State2", RangeA, 2, False)
        .Cells(36, 7) = Application.VLookup("State3", RangeA, 2, False)
        .Cells(37, 7) = Application.VLookup("State4", RangeA, 2, False)
    Else
        .Cells(34, 7) = 0
        .Cells(35, 7) = 0
        .Cells(36, 7) = 0
        .Cells(37, 7) = 0
    End If
End With

End Sub