0

I need to have the user select a range of cells with their mouse and then run a macro to add +1 to that selected range. The range will often be different every time, so it cannot be defined.

Here's what I have so far, it just works on a single active cell, I cannot get it to work on a range selection, because I do not know what to define or function to utilize.

My code Follows:

Sub Add()
ActiveCell.Value = ActiveCell.Value + 1
End Sub

2 Answers 2

3

The below code uses the built-in Paste Special Add feature to add 1 to every cell in the selected range.

Sub AddOneToSelection()

    Dim rBlank As Range

    If TypeName(Selection) = "Range" Then

        'Put a '1' in an unused cell and copy it
        Set rBlank = ActiveSheet.Cells.SpecialCells(xlLastCell).Offset(1, 0)
        rBlank.Value = 1
        rBlank.Copy

        'Paste Special Add over the selection
        Selection.PasteSpecial Paste:=xlPasteValues, _
            Operation:=xlAdd

        'Get rid of the copied cell
        rBlank.ClearContents

    End If

End Sub

The benefit of this over looping is that Paste Special Add treats formulas and values differently and you don't have to code that part yourself.

The downside is you increase your UsedRange by one row, if that matters to you.

1
  • interesting how "Paste Add" handles formulas
    – iDevlop
    Commented Feb 18, 2015 at 16:04
0

This should work for you:

Dim r, c As Range
Set r = Selection

For Each c In r
    c.Value = "+1"
Next

This assumes that your cell formats will display "+1" instead of "1". You can set the format of your cells to "Text".

3
  • user wants to increase by 1, not store 1
    – iDevlop
    Commented Feb 18, 2015 at 16:06
  • @iDevlop -- Not how I'm reading it. If they wanted to increase by 1, they would have just said add 1 to the existing value or increase the existing value by 1, not add "+1" <-- note +1 in quotes, from their title.
    – rory.ap
    Commented Feb 18, 2015 at 16:53
  • Correct, I want to add 1 to the existing value of each of the cells in the user selected range. I should have been more clear. Commented Feb 18, 2015 at 20:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.