复制&如果单元格值=“N / A”,则粘贴值

时间:2016-12-12 04:15:50

标签: excel vba replace copy-paste

我想将值复制并粘贴到一系列单元格中,但前提是它们的值=“N / A”。我想把公式保留在所有不是“N / A”的单元格中。

在上下文中,我有数百个VLOOKUP。例如:

=IFERROR(VLOOKUP("L0"&MID(G$4,1,1)&"A0"&MID(G$4,1,1)&MID(G$4,3,2)&"-0"&$B6,Sheet1!$C:$D,2,FALSE),"N/A")

这可以用VBA吗?

2 个答案:

答案 0 :(得分:0)

首先,您应该使用实际错误值而不是仅看起来像错误的字符串。其次,如果找不到查找值,VLOOKUP会直接返回N/A错误,因此IFERROR包装器可以被取消。所以公式

=VLOOKUP("L0"&MID(G$4,1,1)&"A0"&MID(G$4,1,1)&MID(G$4,3,2)&"-0"&$B6,Sheet1!$C:$D,2,FALSE)

就足够了。

要使用错误值替换N/A结果,您可以使用此

Sub Demo()
    Dim ws As Worksheet
    Dim rngSrc As Range
    Dim datV As Variant, datF As Variant
    Dim i As Long

    ' Get range to process by any means you choose
    '  For example
    Set ws = ActiveSheet
    With ws
        Set rngSrc = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
    End With

    ' Copy data to variant arrays for efficiency
    datV = rngSrc.Value
    datF = rngSrc.Formula

    ' replace erroring formulas
    For i = 1 To UBound(datV, 1)
        If IsError(datV(i, 1)) Then
            If datV(i, 1) = CVErr(xlErrNA) Then
                datF(i, 1) = CVErr(xlErrNA)
            End If
        End If
    Next

    ' return data from variant arrays to sheet
    rngSrc.Formula = datF



End Sub

如果您确实想使用字符串而不是真正的错误值,请调整If行以适应

答案 1 :(得分:0)

您可以使用SpecialCells缩短与=NA()单元格的合作

,而不是遍历某个范围内的所有单元格

这也打开了非VBA方法(如果唯一的错误单元格是NA,即没有Div#/0

  1. 下面的前两种方法(手动和代码)处理您只提供NA个单元格的情况
  2. 第三个使用SpecialCells仅关注需要测试的单元格,然后在进行更新前运行NA检查
  3. <强> 选项1

    手动选择评估错误的公式单元格

    • 选择感兴趣的范围
    • 按[F5]。
    • 点击特殊
    • 选择公式
    • 仅检查错误

    <强> 选项2

    VBA更新评估为错误的公式单元格

    Sub Shorter()
    Dim rng1 As Range
    On Error Resume Next
    ' All error formulas in column A
    Set rng1 = Columns("A").SpecialCells(xlCellTypeFormulas, 16)
    On Error GoTo 0
    If rng1 Is Nothing Then Exit Sub
    'update with new value (could be value or formulae)
    rng1.Value = "new value"
    End Sub
    

    选项3

    测试=NA()

    Sub TestSpecificRegion()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim X
    Dim lngRow As Long
    
    On Error Resume Next
    ' All error formulas in column A
    Set rng1 = Columns("A").SpecialCells(xlCellTypeFormulas, 16)
    On Error GoTo 0
    If rng1 Is Nothing Then Exit Sub
    
    'update with new value (could be value or formulae)
    For Each rng2 In rng1.Areas
        If rng2.Cells.Count > 1 Then
            X = rng2.Value2
            For lngRow = 1 To UBound(X, 1)
                If X(lngRow, 1) = CVErr(xlErrNA) Then X(lngRow, 1) = "new value"
            Next
            rng2.Value = X
        Else
            If rng2.Value2 = CVErr(xlErrNA) Then rng2.Value = "new value"
        End If
    Next
    
    End Sub
    
相关问题