在目标中粘贴 IF 值

Paste IF value in target

我想创建一个宏来复制包含公式的区域 (C2:C22) 并将其作为值粘贴到列区域 (D2:D22) 中。我的问题是每 6 个单元格都有一个公式,我不希望宏覆盖它。 我一直在尝试使用这个宏,但它不复制公式,只复制值,我需要粘贴值,而不是公式。

谢谢!

Sub example()
    Dim source As Range
    Dim target As Range
    Set source = ActiveSheet.Range("c2:c22")
    Set target = ActiveSheet.Range("d2:d22")
    copy_formulas source:=source, target:=target

End Sub

Public Sub copy_formulas(source As Range, target As Range)
    'Assumes that all formulas start with '=' and all non formulas do not
    Dim i As Long
    Dim j As Long
    Dim c As Range

    For i = 1 To source.Rows.Count
        For j = 1 To source.Columns.Count
            Set c = source(RowIndex:=i, ColumnIndex:=j)
            If Left(c.Formula, 1) <> "=" Then
                target(RowIndex:=i, ColumnIndex:=j).Value = c.Value
            End If
        Next j
    Next i
End Sub

将循环内部更改为:

Set c = target(RowIndex:=i, ColumnIndex:=j)
If Left(c.Formula, 1) <> "=" Then
    c.Value = source(RowIndex:=i, ColumnIndex:=j).Value
End If

您当前的代码正在测试 source 单元格中是否有公式,但您的问题暗示您应该测试 target 中的公式 单元格。

这个循环可能更有效率:

Dim rSource As Range
Dim rTarget As Range
Set rSource = Worksheets("Sheet1").Range("C2:C22")
Set rTarget = Worksheets("Sheet1").Range("D2:D22")
For Item = 1 To rSource.Count
   If Not rTarget.Cells(Item).HasFormula Then
      rTarget.Cells(Item).Value = rSource.Cells(Item).Value
   End If
Next Item