1

I would like to copy and paste a formula from column P to column C using a loop in VBA. The code should only copy and paste for numeric values in column P and do nothing when cell is blank.

Sub TestAll()

For i = 10 To 91
Worksheets("Hello").Range("P" & i).Formula = "=" & "MRound(" & Range("C" & 
i).Value & "+$C$7" & ",0.125)"
Next i

Application.CutCopyMode = False

Range("P10:P91").Select
Selection.Copy
Range("C10").Select
Selection.PasteSpecial Paste:=xlPasteFormulasAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False

End Sub
2
  • Your formula has no sense... I can see 3 parameters given to MRound when it only has 2. Does the formula already exists on column P? Commented Apr 15, 2019 at 9:42
  • @Damian: I don't think OP is passing 3 parameters to MRound. Saying that, Robert, please look into why we shouldn't use things like Select or Activate in VBA Commented Apr 15, 2019 at 12:23

2 Answers 2

1

Since you're already using a for loop, you can directly copy the data there.
To check if it's a numeric data, you can use the IsNumeric( Expression ) function and the code could be something like this:

Sub TestAll()

    For i = 10 To 91
        Worksheets("Hello").Range("P" & i).Formula = "=" & "MRound(" & Range("C" & i).Value & "+$C$7" & ",0.125)"

        If (IsNumeric(Worksheets("Hello").Range("P" & i).Value)) Then
            Worksheets("Hello").Range("C" & i).Value = Worksheets("Hello").Range("P" & i).Value
        End If
    Next i

End Sub

Note: Please note that this check is redundant, since the formula will give you always the same result over and over.

Hope this help.

Sign up to request clarification or add additional context in comments.

2 Comments

Value in P column will be 0 f the corresponding cell in column C is blank. Which in this case will still copy the formula over to destination. You might want to put a check for empty cell in column C or a non-numeric value in the corresponding cell
Thanks, Louis - it did help. I managed with your help to construct the answer.
0
Sub TestAll()

For i = 10 To 91
    If (IsEmpty(Worksheets("Hello").Range("C" & i).Value)) 
 Then
    Worksheets("Hello").Range("P" & i).Value = ""
    ElseIf (IsNumeric(Worksheets("Hello").Range("C" & 
i).Value)) Then
    Worksheets("Hello").Range("P" & i).Formula = "=" & 
"MRound(" & Range("C" & i).Value & "+$C$7" & ",0.125)"
    Else
    Worksheets("Hello").Range("P" & i).Value = 
"CALIBRATED"
    End If
Next i

Application.CutCopyMode = False

Range("P10:P91").Select
Selection.Copy
Range("C10").Select
Selection.PasteSpecial 
Paste:=xlPasteFormulasAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False

End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.