将IF值粘贴到目标中

我想要创build一个macros以复制范围(C2:C22),其中有公式并将其粘贴到列范围(D2:D22)上作为值。 我的问题是每6个单元我有一个公式,我不希望macros重写它。 我一直在尝试这个macros,但它不复制公式,只有值,我需要粘贴在值,而不是公式。

谢谢!

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 

您当前的代码正在testing单元格中是否有公式,但是您的问题意味着您应该在目标单元格中testing公式。

这个循环可能更有效率:

 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