如果单元格值是#NV则获取另一个单元格

时间:2016-10-26 09:26:00

标签: excel vba

我已经使用以下代码

    Set sourcerange = Sheets("Sheet1").Range("AW2:AW" & lastRow)
    Set resultrange = Sheets("Sheet2").Range("A2:H" & lastRow)

    i = 1


    For Each cell In sourcerange
        If cell.Value = 1 Then
            resultrange.Rows.Cells(i, 1).Value = Sheets("Sheet1").Range("O" & cell.row).Value
            resultrange.Rows.Cells(i, 2).Value = Sheets("Sheet1").Range("X" & cell.row).Value
            resultrange.Rows.Cells(i, 3).Value = Sheets("Sheet1").Range("P" & cell.row).Value
            resultrange.Rows.Cells(i, 4).Value = Sheets("Sheet1").Range("J" & cell.row).Value
            resultrange.Rows.Cells(i, 5).Value = Sheets("Sheet1").Range("K" & cell.row).Value
            resultrange.Rows.Cells(i, 6).Value = Sheets("Sheet1").Range("G" & cell.row).Value
            resultrange.Rows.Cells(i, 7).Value = Sheets("Sheet1").Range("H" & cell.row).Value
            resultrange.Rows.Cells(i, 8).Value = Sheets("Sheet1").Range("I" & cell.row).Value
            i = i + 1
        End If
Next cell

现在我的问题: 有时会发生这个代码的值:

resultrange.Rows.Cells(i, 2).Value = Sheets("Sheet1").Range("X" & cell.row).Value

是#NV。在这种情况下,我想复制#34; AA"列中的值。但我不知道如何做到这一点。有没有办法在我的代码中添加一些东西才能使它工作?或者我必须重写所有内容吗?

1 个答案:

答案 0 :(得分:0)

你可能想试试这个:

Dim cell As Range

Set SourceRange = Sheets("Sheet1").Range("AW2:AW" & lastRow)
Set ResultRange = Sheets("Sheet2").Range("A2:H" & lastRow)

i = 1

strng = "O X P J K G H I" '<-- list the columns index you want to grab data from, in order
With ResultRange
    For Each cell In SourceRange
        If cell.Value = 1 Then
            .Cells(i, 1).Resize(, 8).FormulaR1C1 = Split("=Sheet1!" & Replace(strng, " ", cell.Row & " =Sheet1!") & cell.Row)
            .Cells(i, 1).Resize(, 8).Value = .Cells(i, 1).Resize(, 8).Value
            If .Cells(i, 2) = "#NV" Then .Cells(i, 2).Value = Sheets("Sheet1").Range("AA" & cell.Row).Value
            i = i + 1
        End If
    Next cell
    .Value = .Value
End With