+ Reply to Thread
Results 1 to 3 of 3

Excel VBA Button Help

Hybrid View

rdroy1754 Excel VBA Button Help 11-29-2016, 12:42 PM
kev_ Re: Excel VBA Button Help 11-30-2016, 02:20 AM
Leith Ross Re: Excel VBA Button Help 12-04-2016, 09:34 PM
  1. #1
    Registered User
    Join Date
    11-29-2016
    Location
    Connecticut
    MS-Off Ver
    2016
    Posts
    2

    Excel VBA Button Help

    Hello. I just recently began to learn about writing code within excel VBA. I have a project for school where I must create a board game and I choose to use excel. I wanted to make a VBA version of connect 4 but was only able to make a mixture of connect 4 and tic tac toe. I am trying to add buttons above the 7 columns of boxes that will drop a chip into an empty column below. Right now, I can click any box and place a chip which is not true to connect 4 seeing that the chips must stack on top of each other. Can any one please help me with the code for this? I've attached a copy.
    Attached Files Attached Files

  2. #2
    Forum Expert
    Join Date
    11-22-2016
    Location
    Cornwall,UK
    MS-Off Ver
    office 365
    Posts
    4,240

    Re: Excel VBA Button Help

    Try this
    (vba checks from bottom to top to see if button contains text and runs the code for the first button it finds which contains no text)
    The code for each of the top row buttons need modifying in the same way

    Private Sub TTTbtn1_Click()
    
    If TTTbtn31.Caption = "" Then
    TTTbtn31_Click
    Exit Sub
        ElseIf TTTbtn25.Caption = "" Then
        TTTbtn25_Click
        Exit Sub
            ElseIf TTTbtn19.Caption = "" Then
            TTTbtn19_Click
            Exit Sub
                ElseIf TTTbtn13.Caption = "" Then
                TTTbtn13_Click
                Exit Sub
                    ElseIf TTTbtn7.Caption = "" Then
                    TTTbtn7_Click
                    Exit Sub
                    
    End If
    
    If Checker = False Then
    TTTbtn1.Caption = "X"
    Checker = True
    Else
    TTTbtn1.Caption = "O"
    Checker = False
    End If
    Call score
    TTTbtn1.Enabled = False
    End Sub
    Last edited by kev_; 11-30-2016 at 02:26 AM.

  3. #3
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,259

    Re: Excel VBA Button Help

    Hello rdroy1954,

    This is a late answer to your post but I hope you will find it useful. The attached workbook has your User form with a modification. Each vertical column has two player buttons "X" an "O". There are 12 total. When the user clicks a button that player's mark is added to the next cell in that column. After each player makes a choice, the macro checks for a win.

    I basically rewrote the code. While your code was working, it lacked the flexibility to accommodate the new changes. You will see this code uses a variety of techniques to simply the and streamline the code. If you were to turn this in as your own project, it would be obvious you had help. My goal is help you see and learn new ways of solving problems with VBA. The code is heavily documented but I am sure you will still have some questions. Please don't hesitate to ask me anything you have a question about.

    Here is the User Form code. The attached workbook contains the new changes and this code.

    Option Explicit
    
    Dim Board       As New Collection
    Dim Checker     As Boolean
    Dim Players()   As Variant
    
    Private Sub EnablePlayerButtons(ByVal State As Boolean)
    
        Dim n As Long
        
            ' Enable or disable the player "X" and "O" buttons.
            For n = 1 To 12
                With Me.Controls("CommandButton" & n)
                    .Enabled = State
                End With
            Next n
    
    End Sub
    
    Private Sub ClearBoard()
    
        Dim n As Long
        
            ' Remove all the players' marks from the board.
            For n = 1 To 36
                With Me.Controls("TTTbtn" & n)
                    .Caption = ""
                    .BackColor = vbButtonFace
                End With
            Next n
    
    End Sub
    
    Private Sub ClearPlayerCounts()
    
            ReDim Players(1 To 2, 1 To 2)
            
            ' Subscripts 1,1 and 2,1 hold the matching cell counts for players.
            ' A player must have 4 consecutive cells to win.
            
            ' The players marks.
            Players(1, 2) = "X"
            Players(2, 2) = "O"
            
    End Sub
    
    Private Sub AddPlayersMark(ByRef Btn As Object)
       
        Dim col     As Integer
        Dim n       As Integer
        Dim Player  As Integer
        Dim row     As Integer
                
            ' Get the column associated with the player's button.
            col = CInt(Btn.Tag)
            
            ' Get the number of the player button that was clicked.
            ' They are named CommandButton1 - CommandButton12.
            n = CInt(Right(Btn.Name, Len(Btn.Name) - 13))
            
            ' Find the next empty space on the board for the column selected
            ' and add the player's mark to the board cell.
            For row = 1 To 6
                With Board(row & "," & col)
                    If .Caption = "" Then
                        Select Case n Mod 2
                            Case 1: Player = 1: .Caption = Players(1, 2): Exit For
                            Case 0: Player = 2: .Caption = Players(2, 2): Exit For
                        End Select
                    End If
                End With
            Next row
            
            ' Enable only one player's buttons at a time.
            If Player = 1 Then
                For n = 1 To 11 Step 2
                    Me.Controls("CommandButton" & n).Enabled = False
                    Me.Controls("CommandButton" & n + 1).Enabled = True
                Next n
            End If
            
            ' Enable only one player's buttons at a time.
            If Player = 2 Then
                For n = 1 To 11 Step 2
                    Me.Controls("CommandButton" & n).Enabled = True
                    Me.Controls("CommandButton" & n + 1).Enabled = False
                Next n
            End If
            
            'Check for a winner.
            If Player <> 0 Then
                Call CheckForWinner(row & "," & col)
            End If
        
    End Sub
    
    Private Sub CheckForWinner(ByVal Btn_Name As String)
    
        Dim col     As Long
        Dim j       As Long
        Dim k       As Long
        Dim n       As Long
        Dim Player  As Integer
        Dim row     As Long
        
            ' Check all six directions from the current board cell chosen.
        
            ' Reset the Players' marks count to zero.
            ClearPlayerCounts
            
            ' Determine the row and column on the board for the button that was clicked.
            row = Split(Btn_Name, ",")(0)
            col = Split(Btn_Name, ",")(1)
            
            ' Get the player number by matching the caption of the player button to the players marks.
            For n = 1 To UBound(Players)
                If Board(row & "," & col).Caption = Players(n, 2) Then
                    Player = n
                End If
            Next n
            
            ' Check / Diagonal entries.
            ' Moving Up the vector.
                ClearPlayerCounts
                j = row
                k = col
                
                Do
                    GoSub TestForWin
                    k = k + 1
                    j = j + 1
                    If j > 6 Or k > 6 Then Exit Do
                Loop
                
            ' Check / Diagonal entries.
            ' Moving Down the vector.
                ClearPlayerCounts
                j = row
                k = col
                
                Do
                    GoSub TestForWin
                    k = k - 1
                    j = j - 1
                    If j < 1 Or k < 1 Then Exit Do
                Loop
            
            ' Check \ Diagonal entries.
            ' Moving Up the vector.
                ClearPlayerCounts
                j = row
                k = col
                
                Do
                    GoSub TestForWin
                    k = k + 1
                    j = j - 1
                    If j < 1 Or k > 6 Then Exit Do
                Loop
            
            ' Check \ Diagonal entries.
            ' Moving Down the vector.
                ClearPlayerCounts
                j = row
                k = col
                
                Do
                    GoSub TestForWin
                    k = k - 1
                    j = j + 1
                    If j > 6 Or k < 1 Then Exit Do
                Loop
            
            ' Check - Horizontal entries.
                ClearPlayerCounts
                j = row
                k = col
                
                For k = 1 To 6
                    GoSub TestForWin
                Next k
            
            ' Check | Vertical entries.
                ClearPlayerCounts
                j = row
                k = col
                
                For j = 1 To 6
                    GoSub TestForWin
                Next j
           
    Exit Sub
    
    ' Player must have 4 consecutive board cells with his or her mark in them to win.
    TestForWin:
                DoEvents
                
                    If Board(j & "," & k).Caption = Players(Player, 2) Then
                        Players(Player, 1) = Players(Player, 1) + 1
                        ' Check for a win.
                        If Players(Player, 1) = 4 Then
                            MsgBox "Player """ & Players(Player, 2) & """ Wins!"
                            EnablePlayerButtons State:=False
                            ' Update the winner's game total.
                            Select Case Player
                                Case 1: Me.Label3.Caption = CInt(Me.Label3.Caption) + 1
                                Case 2: Me.Label4.Caption = CInt(Me.Label4.Caption) + 1
                            End Select
                            Exit Sub
                        End If
                    Else
                        ' Player was not a winner. Clear the board cell count.
                        Players(Player, 1) = 0
                    End If
                
                Return
    
    End Sub
    
    Private Sub CommandButton1_Click()
            AddPlayersMark Me.Frame1.ActiveControl
    End Sub
    
    Private Sub CommandButton10_Click()
            AddPlayersMark Me.Frame1.ActiveControl
    End Sub
    
    Private Sub CommandButton11_Click()
            AddPlayersMark Me.Frame1.ActiveControl
    End Sub
    
    Private Sub CommandButton12_Click()
            AddPlayersMark Me.Frame1.ActiveControl
    End Sub
    
    Private Sub CommandButton2_Click()
            AddPlayersMark Me.Frame1.ActiveControl
    End Sub
    
    Private Sub CommandButton3_Click()
            AddPlayersMark Me.Frame1.ActiveControl
    End Sub
    
    Private Sub CommandButton4_Click()
            AddPlayersMark Me.Frame1.ActiveControl
    End Sub
    
    Private Sub CommandButton5_Click()
            AddPlayersMark Me.Frame1.ActiveControl
    End Sub
    
    Private Sub CommandButton6_Click()
            AddPlayersMark Me.Frame1.ActiveControl
    End Sub
    
    Private Sub CommandButton7_Click()
            AddPlayersMark Me.Frame1.ActiveControl
    End Sub
    
    Private Sub CommandButton8_Click()
            AddPlayersMark Me.Frame1.ActiveControl
    End Sub
    
    Private Sub CommandButton9_Click()
            AddPlayersMark Me.Frame1.ActiveControl
    End Sub
    
    Private Sub TTTbtn37_Click()
        
    ' Reset Game
    
        ClearBoard
        EnablePlayerButtons State:=True
        
    End Sub
    
    Private Sub TTTbtn38_Click()
    
    ' New Game
    
        Call ClearBoard
        Me.Label3.Caption = "0"
        Me.Label4.Caption = "0"
        EnablePlayerButtons State:=True
        
    End Sub
    
    Private Sub UserForm_Initialize()
    
        Dim Btn As Object
        Dim j   As Integer
        Dim k   As Integer
        Dim n   As Integer
        
            ClearPlayerCounts
            
            ' Set the Tag equal to the column number for the player buttons "X" and "O".
            For k = 1 To 12 Step 2
                n = n + 1
                Me.Frame1.Controls("CommandButton" & k).Tag = n
                Me.Frame1.Controls("CommandButton" & (k + 1)).Tag = n
            Next k
            
            n = 0
            
            ' Save the Board cells (CommandButtons) and their x,y coordinates in the collection named Board.
            ' The collection returns a Board cell (CommandButton object) referenced by "x,y".
            For j = 31 To 1 Step -6
                n = n + 1
                ' Save the column the cell belongs to using the Tag property.
                For k = 0 To 5
                    Me.Frame1.Controls("TTTbtn" & (j + k)).Tag = n
                    Set Btn = Me.Frame1.Controls("TTTbtn" & (j + k))
                    Board.Add Btn, n & "," & (k + 1)
                Next k
            Next j
            
    End Sub
    Attached Files Attached Files
    Last edited by Leith Ross; 12-04-2016 at 09:36 PM.
    Sincerely,
    Leith Ross

    Remember To Do the Following....

    1. Use code tags. Place [CODE] before the first line of code and [/CODE] after the last line of code.
    2. Thank those who have helped you by clicking the Star below the post.
    3. Please mark your post [SOLVED] if it has been answered satisfactorily.


    Old Scottish Proverb...
    Luathaid gu deanamh maille! (Rushing causes delays!)

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Excel 2013 won't run a macro attached to button created in excel 2003
    By Jonno1 in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 04-30-2020, 01:16 AM
  2. [SOLVED] Form - select button & retrieve button name or button's caption
    By lexusap in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 09-27-2016, 12:28 AM
  3. vba code to disable only close button and close through a button in Excel workbook
    By atif_ar in forum Excel Programming / VBA / Macros
    Replies: 47
    Last Post: 11-23-2014, 02:41 PM
  4. VBA Code to Disable Excel Close button also disabling my Close Button
    By akynyemi in forum Excel Programming / VBA / Macros
    Replies: 0
    Last Post: 12-28-2013, 12:56 PM
  5. Macro button to save file in excel, format of excel
    By sunshne900 in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 10-01-2013, 02:40 PM
  6. BUTTON TO CLOSE AND OPEN EXCEL FILE( excel vba)
    By TRADER_M in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 11-08-2012, 08:48 PM
  7. Disable 'Exit Excel' button in Excel 2007
    By Testing213 in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 07-25-2008, 01:30 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1