如何使用按钮在excel vba中创建它?

时间:2018-03-10 19:54:15

标签: excel-vba vba excel

“这是一个简单,快速的形式来告诉我想做什么。我知道这不完整,我只是想告诉你我是如何想象它的内在运作的优点。(我问过我的一所大学快速写下来:))

我们只需要通过按钮旋转4个,如下所示:

             Class State
           {
            enum RowStates {White:0,Red:1;Yellow:2,Green:3}
            //White is the basic state.Nothing has  //happened,only 
            recording
            //Red is failed
            //Yellow is problematic/under production
            //Green is all done.

             int states = 0;
             //state counter helper number
             RowStates CurrentState=(enum)states;

             Static Void ButtonPressed(event args stuff...)
             {
            If(states!=3)
            states++;
            //this makes the steps further
            //which results color change
            else
            states=0;
            //this resets the states to white
            }
            }

如何使用宏在excel中创建它?

1 个答案:

答案 0 :(得分:0)

我不太确定你的目标是什么,但是当你的同事写下来时,你可能会看一下类州的以下代码

    Option Explicit

    Enum RowStates
        white = 0
        red = 1
        yellow = 2
        green = 3
    End Enum

    Dim states As Byte

    Property Get CurrentState() As RowStates
        CurrentState = states
    End Property

    Public Function ButtonPressed() As RowStates

        If states <> 3 Then
            states = states + 1
        Else
            states = 0
        End If

    End Function

这是Java / C代码

的一种“逐个”翻译

编辑让我们稍微更改类状态,以便在工作表中切换某个范围的颜色。

Option Explicit

Enum RowStates
    White = 0
    Red = 1
    Yellow = 2
    Green = 3
End Enum

Dim states As Byte

Public Function ButtonPressed() As RowStates

    If states <> 3 Then
        states = states + 1
    Else
        states = 0
    End If

End Function

Property Get Color() As Long

    Select Case states
    Case RowStates.White
        Color = vbWhite
    Case RowStates.Red
        Color = vbRed
    Case RowStates.Yellow
        Color = vbYellow
    Case RowStates.Green
        Color = vbGreen
    End Select

End Property

然后在工作表上放置一个Active-X按钮,并将以下代码添加到工作表模块

Option Explicit
Dim btnState As New state
Private Sub CommandButton1_Click()

    With btnState
        .ButtonPressed
        Range("A4:Q4").Interior.Color = .Color
    End With

End Sub

EDIT2 但TO的请求更容易实现恕我直言。只需在Sheet1上放置一个按钮,然后为其分配以下代码即可。没有真正需要上课。

Option Explicit

Sub Button_Click()

Dim rg As Range
Static btnPressed As Byte

    Set rg = Sheet1.Range("A4:Q4")

    If btnPressed = 3 Then
        btnPressed = 0
    Else
        btnPressed = btnPressed + 1
    End If

    Select Case btnPressed
    Case 0
        rg.Interior.Color = vbWhite
    Case 1
        rg.Interior.Color = vbRed
    Case 2
        rg.Interior.Color = vbYellow
    Case 3
        rg.Interior.Color = vbGreen
    End Select

End Sub