将"1"添加到范围内的所有单元格

ack*_*ddy 2 excel vba excel-2007 excel-vba

我正在尝试1在一个范围内添加一个单元到多个单元格.下面是我的位置,我不断收到类型不匹配错误:

Dim r As Range, cell As Range

Set r = Range("D2:E1000")

For Each cell In r
    If cell.Value > 0 Then
        cell.Value = cell.Value + 1
    End If
Next
Run Code Online (Sandbox Code Playgroud)

Dic*_*ika 5

这是另一种方式

Sub Sandwich()

    Dim rTemp As Range
    Dim rTarget As Range
    Dim sNumFmt As String

    'Define the ranges
    Set rTemp = Sheet2.Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0)
    Set rTarget = Sheet2.Range("D2:E1000")

    'store a temporary value and the current number format
    rTemp.Value = 1
    sNumFmt = rTarget.Cells(1).NumberFormat

    'copy and paste special-add
    rTemp.Copy
    rTarget.PasteSpecial , xlPasteSpecialOperationAdd

    'get rid of the temp and reapply the format
    rTemp.ClearContents
    rTarget.NumberFormat = sNumFmt

End Sub
Run Code Online (Sandbox Code Playgroud)