PDA

View Full Version : VBE Programming buttons in Excel



Zhouse92
02-15-2023, 07:39 AM
Hi,

I have been using ChatGPT to help in creating a macro for hiding/unhiding buttons in excel based on value in certain cells and it keeps getting overloaded and telling to return in an hour - so here I am to get some help.

I am trying to get A start/stop button that inserts a click counter in cell B3, date/time in cell C3 for start click, date/time in cell D4 for end time, elapsed time in cell E3, and the start stop buttons hide or unhide based on data in cell A3 so I can have multiple buttons based on certain assets that are selected from the drop down list.


I was able to get the code to count the clicks and input all the date/time data. But as soon as I started with the hide/unhide my macros wouldn't work anymore. Does nothing when I select the button, no errors or anything.

Start button name is Button4 and stop button name is button5

My code is as follows:


Private Sub Button4(ByVal Target As Range)
If Range("A3").Value = "Strata Backless Bench Mold: 1" Then
'Show the buttons
Call ShowButton("Start", True)
Call ShowButton("Stop", True)
Else
' Hide the buttons
Call ShowButton("Start", False)
Call ShowButton("Stop", False)
End If
End Sub


Private Sub ShowButton(ByVal btnName As String, ByVal show As Boolean)
' Get the button with the given name
Dim btn As Shape
For Each btn In ThisWorkbook.Sheets("Sheet1").Shapes
If btn.Name = Button4 Then
btn.Visible = show
Exit For
End If
Next btn
End Sub


Private Sub Start_Click()
' Increase the counter
Range("B3").Value = Range("B3").Value + 1
' Store the start time
Range("C3").Value = Now()
End Sub


Private Sub Stop_Click()
' Store the stop time
Range("D3").Value = Now()
' Calculate the elapsed time
Range("E3").Value = Range("D3").Value - Range("C3").Value
End Sub

Sub moldtracker_stop_Click()

End Sub


Any help with this is appreciated

Artik
02-19-2023, 10:02 AM
The error is in the ShowButton procedure in line
If btn.Name = Button4 Then
It should be

If btn.Name = "Button4" Then
But you can write this procedure more simply:
Private Sub ShowButton(ByVal btnName As String, ByVal show As Boolean)
On Error Resume Next
ThisWorkbook.Sheets("Sheet1").Shapes(btnName).Visible = show
On Error GoTo 0
End Sub
Artik