2017-09-05 76 views
0

我想創建一個宏來複制其中有公式的範圍(C2:C22)並將它粘貼到列範圍(D2:D22)上作爲值。我的問題是每6個單元我有一個公式,我不希望宏覆蓋它。 我一直在嘗試這個宏,但它不復制公式,只有值,我需要粘貼在值,而不是公式。將IF值粘貼到目標中

謝謝!

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 
+0

你的問題說: 「我一直在試圖與這個宏,但它不會複製公式,只值,我需要粘貼值,而不是在公式上。「 這聽起來像是在做你需要的東西。你能澄清嗎? –

+0

@ChrisMoore OP正試圖在不覆蓋現有公式的情況下複製值 –

回答

2

更改你的循環裏面:

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

您當前的代碼檢測是否有在單元格的公式,但你的問題意味着你應該爲被測試公式在目標單元格中。

+0

使錯誤代碼看起來錯誤101:'c'是一個糟糕的標識符 - 如果'c'被命名爲'targetCell',則不會發生此錯誤...假設'Set targetCell = source(...)'看起來不夠好 –

+0

非常感謝。我真的被卡住了!你解決我的問題:) – Diego

0

這個循環可能更有效:

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 
+0

謝謝託尼,我真的很感激它:) – Diego

+0

我該如何添加多個範圍到這個循環?我嘗試了下面,但它只複製/粘貼第一個範圍Z18:AA250 - AU18:AV250 Dim rSource As Range Dim rTarget As Range Set rSource = ActiveSheet.Range(「Z18:AA250,W18:X250,H18: H250,O18:O250「) 設置rTarget = ActiveSheet.Range(」AU18:AV250,AX18:AY250,AR18:AR250,AS18:AS250「) For Item = 1 To rSource.Count If rTarget.Cells(Item ).HasFormula Then rTarget.Cells(Item).Value = rSource.Cells(Item).Value End If Next Item – Diego