如何使用Excel中的按钮编辑几个可能的单元格之一

时间:2018-01-24 03:10:14

标签: excel vba excel-vba excel-2016

我正在处理Excel 2016文档,我有一个名称和点的表,以及一个默认值,格式如下:

Name   Default   Points
Bill     50        10            Jim <-- This is a cell outside of the table,
Jim      16        32                   that displays the name that is "selected."
Sam       5         8

目前,我有三个按钮(一个用于递增Points列中的数字,一个用于递减数字,一个用于重置为Default列中的值),使用此基本VBA代码为每个名称设置:< / p>

Private Sub CommandButton1_Click()
    Range("C3").Value = Range("C3").Value + 1   <-- for the increment button
End Sub
                      [OR]
Private Sub CommandButton2_Click()
    Range("C3").Value = Range("C3").Value - 1   <-- for the decrement button
End Sub
                      [OR]
Private Sub CommandButton3_Click()
    Range("C3").Value = Range("B3").Value       <-- for the reset button
End Sub

有没有办法只引入三个按钮,并设置它们,以便每个按钮可以用于列表中任何一个名称的点值?

例如,如果我选择了Jim(如上面的表格示例中所示),按钮将识别出Jim被选中,找到与Jim(32)相关联的点值,并编辑该值)?

1 个答案:

答案 0 :(得分:0)

假设:

  1. 所选单元格文字位于“G3”
  2. “名称”列中的名称不得超过34个
  3. 此外,我们假设您将相应的Sub分配给按钮。

    Sub IncrementButton_Click()
        TakeAction "Increment"
    End Sub
    Sub DecrementButton_Click()
        TakeAction "Decrement"
    End Sub
    Sub ResetButton_Click()
        TakeAction "Reset"
    End Sub
    
    Sub TakeAction(ByVal action As String)
    
        Dim r As Integer
        Dim foundCell As Range
        Set foundCell = Range("a2", "a35").Find(Cells(3, 7).Text)
        If Not (foundCell Is Nothing) Then
            r = foundCell.Row
        Else
            MsgBox "Couldn't find the current selection."
            Exit Sub
        End If
    
        Select Case LCase(action)
            Case "increment"
                Cells(r, 3) = Cells(r, 3) + 1
            Case "decrement"
                Cells(r, 3) = Cells(r, 3) - 1
            Case "reset"
                Cells(r, 3) = Cells(r, 2)
        End Select
    
    End Sub