Excel

Use a Command Button as Toggle Button

Ease of Use

Intermediate

Version tested with

2000 

Submitted by:

johnske

Description:

On running the code the command buttons size and caption alternates. 

Discussion:

It's not always desirable to use a standard toggle button, this code uses a single command button to demonstrate how to use an If-Then-Else statement to alternate between two different states. Its' use is not restricted to command buttons, the same technique can also be used with most other controls. 

Code:

instructions for use

			

'************************************ '<< CODE FOR THE ThisWorkbook MODULE >> Option Explicit Private Sub Workbook_Open() With Sheet1.CommandButton1 .Height = 20 .Width = 60 .Left = 150 .Top = 80 .Caption = "Click Me" End With End Sub '************************************ '************************************ '<< CODE FOR THE SHEET1 MODULE >> Option Explicit Private Sub CommandButton1_Click() With CommandButton1 .Height = 20 .Width = 60 If .Caption = "Click Me" Then .Width = 180 .Font.Bold = True .Caption = "Ohh YES, I Like That! - Do It Again!!" Else .Width = 60 .Font.Bold = False .Caption = "Click Me" End If End With End Sub '************************************

How to use:

  1. Open a new Excel workbook
  2. Select Tools/Macro/Visual Basic Editor
  3. In the VBE window, select Tools/Project Explorer
  4. Select the ThisWorkbook module
  5. Copy and paste the 'ThisWorkbook' code into this Module
  6. Select the Sheet1 module
  7. Copy and paste the 'Sheet1' code into this Module
  8. Now select File/Close and Return To Microsoft Excel
  9. Select View/Toolbars/Control Toolbox and click Command Button
  10. Place the mouse pointer on the worksheet and draw it down & to the right
  11. Close the Control Toolbox (click the X)
  12. Save and close the workbook...
 

Test the code:

  1. Open the workbook and click the command button - repeat
 

Sample File:

ToggleItFun.zip 9.48KB 

Approved by mdmackillop


This entry has been viewed 236 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express