简体   繁体   中英

Macro button to change cell values

I found this link on Stack Overflow, and it did help a lot: Change Cell Values with Macro . I used the answer provided by @Jeeped.

This changes cell values from 1 to 7 by macro button presses. When it reaches 7 it starts from 1 again.

But, I would like to use TWO buttons, one counting down, the other up, and, when reaching 1 the downcounting button presses shouldn't affect the digits any more, to change you would have to press UP button to count up from the number 1.

How should I do this?

I am assuming you want to mimic the behaviour of the other question in that the buttons move the target value through a list of values found in a range. This is obviously different to simply incrementing or decrementing a value.

Caveat: as per the other question, this requires that the values in the list are unique.

The following is similar to the code from the other question. It moves down the table. Difference: it stops at the last value (does not go back to the start).

Sub ButtonDown_Click()
    Dim targetCell As Range
    Set targetCell = Range("A1")
    Dim tableRange As Range
    Set tableRange = Range("B1:B10")
    If IsError(Application.Match(targetCell.Value, tableRange, 0)) Then
        'if value in the target cell is not in the table then reset to the first value in table
        targetCell.Value = tableRange.Cells(1).Value
    ElseIf Application.Match(targetCell.Value, tableRange, 0) < tableRange.Cells.Count Then
        'if value in the target cell is NOT the last value in the table then move to the next value in the table
        targetCell.Value = tableRange.Cells(1).Offset(Application.Match(targetCell.Value, tableRange, 0), 0).Value
    End If
End Sub

The following is code for another button which moves up through the table. It stops when it gets to the first value.

Sub ButtonUp_Click()
    Dim targetCell As Range
    Set targetCell = Range("A1")
    Dim tableRange As Range
    Set tableRange = Range("B1:B10")
    If IsError(Application.Match(targetCell.Value, tableRange, 0)) Then
        'if value in the target cell is not in the table then reset to the first value in table
        targetCell.Value = tableRange.Cells(1).Value
    ElseIf Application.Match(targetCell.Value, tableRange, 0) > 1 Then
        'if value in the target cell is NOT the first value in the table then move to the previous value in the table
        targetCell.Value = tableRange.Cells(1).Offset(Application.Match(targetCell.Value, tableRange, 0) - 2, 0).Value
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM