在 VBA 中使用循环复制和粘贴时如何跳过非数字值?

How can I skip non-numeric values when copy and paste using loop in VBA?

我想使用 VBA 中的循环将公式从 P 列复制并粘贴到 C 列。该代码应该只复制和粘贴 P 列中的数值,并且在单元格为空白时不执行任何操作。

Sub TestAll()

For i = 10 To 91
Worksheets("Hello").Range("P" & i).Formula = "=" & "MRound(" & Range("C" & 
i).Value & "+$C" & ",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

由于您已经在使用 for 循环,您可以直接将数据复制到那里。
要检查它是否是 numeric 数据,您可以使用 IsNumeric( Expression ) function 并且代码可能是这样的:

Sub TestAll()

    For i = 10 To 91
        Worksheets("Hello").Range("P" & i).Formula = "=" & "MRound(" & Range("C" & i).Value & "+$C" & ",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.

希望对您有所帮助。

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" & ",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