vba - 将 '1' 添加到范围内的所有单元格

标签 vba excel 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

最佳答案

还有另一种方法

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

关于vba - 将 '1' 添加到范围内的所有单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19821151/

相关文章:

VBA 暂停代码并等待用户交互

Excel:根据另一列中的值和映射值求和值

vba - Visual Basic - 变量名自动递增/循环

excel - 添加新行并格式化添加的新行

mysql - 使用 VBA 执行在文本框中编写的 SQL

excel - 搜索查找值对(在列的 D、E 中)是否存在于查找数组(在列的 A、B 中)的脚本/宏

VBA Excel : filter with "or" condtion between 2 columns

excel - 使用 Excel 工作表作为模板与 OpenXML 中的 "real"Excel 模板

VBA - 存储值会改变的单元格的值的最佳方式

ms-access - 自定义 VBA 函数中的智能感知功能?