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

时间:2013-11-06 19:33:37

标签: excel vba excel-vba excel-2007

我试图将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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

怎么样:

Sub marine()
    Dim r As Range, cell As Range

    Set r = Range("D2:E1000")

    For Each cell In r
        If IsNumeric(cell.Value) Then
            If cell.Value > 0 Then
                cell.Value = cell.Value + 1
            End If
        Else
            MsgBox "Cell " & cell.Address(0, 0) & " does not have a number"
            Exit Sub
        End If
    Next
End Sub

答案 2 :(得分:3)

OK, I'm trying to add a unit of "1" to many cells in a range.最简单的方式停止通常没有VBA或代码。只需在电子表格的某处插入1,复制该单元格,选择感兴趣的范围,然后使用操作添加选择性粘贴。然后可以删除1

答案 3 :(得分:0)

Dim r As Range, cell As Range

Set r = Range("D2:E1000")

For Each cell In r
    If cell > 0 Then
        cell.Value = cell.Value + 1
    End If
Next

为我工作,也许你想要IF cell = 0 ??? 等待你的评论,看看我是否提出了你的问题。