How to stop a macro by clicking a command button? - vba

I have a code to copy a range and paste the values.
This is done in a time interval after I click a command button.
How do I stop or pause this macro by clicking a button?
Here is the main code:
Sub timestamp()
'
' timestamp Macro
'
N = WorksheetFunction.Count(Sheets("DNB").Columns(1))
dnbspread = Sheets("DNB").Range("G5:G30")
Sheets("DNB").Cells(N + 34, 1) = Date
Sheets("DNB").Cells(N + 34, 2) = Time
Sheets("DNB").Range("G5:G30").Copy
Sheets("DNB").Cells(N + 34, 3).PasteSpecial Transpose:=True, Paste:=xlPasteValues
Application.OnTime Now + TimeValue("00:00:05"), "timestamp"
End Sub
I tried a couple of things.
by BREAK function
Sub PauseMacro()
Application.SendKeys "^{BREAK}"
End Sub
2.
Public StopMacro as Boolean
Sub SetStopMacro()
StopMacro = True
End Sub
and put it in the code as this:
Sub timestamp()
'
' timestamp Macro
'
N = WorksheetFunction.Count(Sheets("DNB").Columns(1))
dnbspread = Sheets("DNB").Range("G5:G30")
Sheets("DNB").Cells(N + 34, 1) = Date
Sheets("DNB").Cells(N + 34, 2) = Time
Sheets("DNB").Range("G5:G30").Copy
Sheets("DNB").Cells(N + 34, 3).PasteSpecial Transpose:=True, Paste:=xlPasteValues
Application.OnTime Now + TimeValue("00:00:10"), "timestamp"
DoEvents
If StopMacro = True Then Exit Sub
End Sub

Public StopMacro As Boolean
Sub SetStopMacro()
StopMacro = True
End Sub
Sub timestamp()
'
' timestamp Macro
'
' code here
'
' Put If-Then before Application.OnTime call.
' So prevent next call of 'timestamp()' if StopMacro equals to true
If Not StopMacro Then
Application.OnTime Now + TimeValue("00:00:15"), "timestamp"
End If
End Sub

You can declare a global variable inside the module where the macro is running from, and then, when the command button is clicked, assign a value to that variable you just declared. Then, create an if statement, where the code exits if the variable equals to that value.
Private Sub CommandButton2_Click()
btncancel = 1
EMSetup.hide
Exit Sub
End Sub
For the command button.
Global btncancel As Integer
If btncancel = 1 Then
Exit Sub
End If
Hope this helps!

Related

Can not run macro The macro may not be available in this workbook or all marcos may be disabled

I am trying to ad a activity (in this example print time) after every 5 second by following code.
Sub tr1()
dim i as Integer
i = Range("b1").Value
If i < 3 Then
Application.OnTime Now + TimeValue("00:00:05"), "tr2", , True
End If
Range("a" & i).Value = UCase(Format(Now, "HH:MM:SS"))
Range("b1").Value = Range("b1").Value + 1
MsgBox ("tr1 called")
End Sub
Sub tr2()
Application.OnTime Now + TimeValue("00:00:05"), "tr1"
MsgBox ("tr2 called")
End Sub
on running tr1, I am getting following error:
after 5 seconds. Please, let me what am I doing wrong.
You have to refer the module as well. This will work, if the code is in Module1:
Sub tr1()
Application.OnTime Now + TimeValue("00:00:01"), "!Module1.tr2", , True
End Sub
Sub tr2()
MsgBox "tr2"
End Sub
If it is in a worksheet, the correspondingly:
Sub tr1()
Application.OnTime Now + TimeValue("00:00:01"), "!Sheet1.tr2", , True
End Sub
Sub tr2()
MsgBox "tr2"
End Sub

Passing an user form result to vba code variable

I have a code that counts the files in a folder if they contain a specific string on their name.
For example: If I want it to count the files with close on their name (Close_26_03_2003.csv).
Currently the code reads the value of a cell in the sheet and searches for that string in the file name with the (InStr function). Problem is I have to write the type of file in the cell.
What I am trying to do is create an user form, with three option buttons (open, close and cancel). For open it sets the string equal to open, and search for files that have it on their name (same as for close). Cancel ends the sub.
Problem is I don't know which code I have to use in the user form for this and don't know how to pass it to the code that counts files (I though about assigning it to a variable).
Code as is:
Sub CountFiles3()
Dim path As String, count As Integer, i As Long, var As Integer
Dim ws As Worksheet
Dim Filename As String
Dim FileTypeUserForm As UserForm1
Application.Calculation = xlCalculationManual
path = ThisWorkbook.path & "\*.*"
Filename = Dir(path)
'the problem is here:
'x = user form result***************
'if cancel = true, end sub
Set ws = ThisWorkbook.Sheets("FILES")
i = 0
Do While Filename <> ""
'var = InStr(Filename, ws.Cells(2, 7).Value) 'this is current code, it checks if the cell has open or close
var = InStr(Filename, x)
If var <> 0 Then
i = i + 1
ws.Cells(i + 1, 1) = Filename
Filename = Dir()
Else: Filename = Dir()
End If
Loop
Application.Calculation = xlCalculationAutomatic
ws.Cells(1, 2) = i
MsgBox i & " : files found in folder"
End Sub
And this is my current user form code:
Private Sub Cancel_Click()
Me.Tag = 3 ' EndProcess
Me.Hide
End Sub
Private Sub ClosingType_Click()
Me.Tag = 2 ' "CLOSING"
Me.Hide
End Sub
Private Sub OpeningType_Click()
Me.Tag = 1 ' "OPENING"
Me.Hide
End Sub
Any ideas?
add following code to your CountFiles3() sub in the "'the problem is here:" section:
Dim x As String
x = GetValue
If x = "end" Then Exit Sub
then add following code in any module:
Function GetValue()
With MyUserForm '<--| change "MyUserForm " to your actual UserForm name
.Show
GetValue = .Tag
End With
Unload MyUserForm '<--| change "MyUserForm " to your actual UserForm name
End Function
and change your Userform code as follwos
Private Sub Cancel_Click()
Me.Tag = "end" ' EndProcess
Me.Hide
End Sub
Private Sub ClosingType_Click()
Me.Tag = "close" ' "CLOSING"
Me.Hide
End Sub
Private Sub OpeningType_Click()
Me.Tag = "open" ' "OPENING"
Me.Hide
End Sub

Prevent On.Time from running multiple times

I have the following macro assigned to a button:
Sub refresh()
Application.Calculation = xlCalculationManual
ActiveWorkbook.RefreshAll
Application.Calculation = xlCalculationAutomatic
Call repeat
End Sub
Sub repeat()
TimeToRun = Now + TimeValue("00:05:00")
Application.OnTime TimeToRun, "refresh"
End Sub
If the button is clicked more than once, I get multiple instances of this macro running.
Is there a way to cancel any macros running prior to commencing the Sub refresh()?
Something like this:
Dim TimeToRun
Sub refresh()
Application.Calculation = xlCalculationManual
ActiveWorkbook.RefreshAll
Application.Calculation = xlCalculationAutomatic
Call repeat
End Sub
Sub repeat()
If TimeToRun > 0 Then
'cancel previous...
Application.OnTime TimeToRun, "refresh", False
End If
TimeToRun = Now + TimeValue("00:05:00")
Application.OnTime TimeToRun, "refresh"
End Sub
I tried to add the cancellation code in repeat but it did not work. I have added another sub that should run when the button is clicked. Range("G1") is a cell i use to store the time value.
Sub refresh()
Application.Calculation = xlCalculationManual
ActiveWorkbook.RefreshAll
Application.Calculation = xlCalculationAutomatic
Call repeat
End Sub
Sub repeat()
TimeToRun = Now + TimeValue("00:00:10")
'stoer the TimeToRun
Range("G1") = TimeToRun
'schedule the next refresh
Application.OnTime EarliestTime:=TimeToRun, Procedure:="refresh", Schedule:=True
End Sub
Sub subForClick()
If Not (IsEmpty(Range("G1"))) Then
Application.OnTime EarliestTime:=Range("G1").Value, Procedure:="refresh", Schedule:=False
End If
Call refresh
End Sub
Late for the party, but I create a function to check the time and let the user run the code again after some time.
Private Function timeCheck() As Boolean
If VBA.Now() > TimeControl.Range("A1").Value + VBA.TimeValue("00:05:00") Then
timeCheck = True
Else
timeCheck = False
End If
End Function
Where TimeControl is the name of the sheet that holds the time value on range A1.
So you just need to use this function as below:
If timeCheck = True Then
TimeControl.Range("A1").Value = VBA.Now()
do something
else
do something else
end if

Countdown after button click

I would like to make a countdown, so I've set a cell, E1 with time format, and given 0:02:55 as start time. After that I try to make coutdown after button click with this code, but got an error, that it isn't runnable.
Sub Timer()
Dim gCount As Date
gCount = Now + TimeValue("00:00:01")
Application.OnTime gCount, "ResetTime"
End Sub
Sub ResetTime()
Dim xRng As Range
Set xRng = Application.ActiveSheet.Range("E1")
xRng.Value = xRng.Value - TimeSerial(0, 0, 1)
If xRng.Value <= 0 Then
MsgBox "Countdown complete."
Exit Sub
End If
Call Timer
End Sub

VBA - Open form within loop then wait for OK click

I have a script that checks for new shops in a sheet. If it finds a new shop it should open a form and prompt the user to select a shop category and then click ok. When the the user clicks ok the value from the dropdown should be selected and then form closes and the loop continues.
The form is calles "shopkat"
This is how it works:
For i = LBound(distshops) To UBound(distshops)
If Not IsEmpty(distshops(i)) Then
curcell = getrows
curshop = distshops(i)
findout = checkifinsheet(curshop)
If findout = False Then
Cells(curcell + 1, 1) = curshop
'show form
shopkat.Show vbModal
'shop current shop
shopkat.shop.Caption = curshop
'Get value from combo
Cells(curcell + 1, 2) = shopkat.shopkatcombo.value
'if user click ok then continue
End If
End If
Next i
Could anyone help. Thanks a lot!
//////////////////////////// Updated ///////////////////////////////
Module1:
Public curcell As Long
Dim ws As Worksheet
Form shopkat:
Private Sub shopkatok_Click()
If Not shopkat.shopkatcombo.value = "" Then
ws.Cells(curcell + 1, 2) = shopkat.shopkatcombo.value
Unload Me
End If
End Sub
Loop Sheet(Shopcategories)
Set ws = ThisWorkbook.Sheets("Shopcategories")
For i = LBound(distshops) To UBound(distshops)
If Not IsEmpty(distshops(i)) Then
curcell = getrows()
curshop = distshops(i)
findout = checkifinsheet(curshop)
If findout = False Then
shopkat.shop.Caption = curshop
'show form
shopkat.Show
If Not IsEmpty(Cells(curcell + 1, 2).value) Then
ws.Cells(curcell + 1, 1) = curshop
End If
End If
End If
Next i
Ok Do this. (UNTESTED)
A) Insert a module and paste these lines
Public curcell As Long
Dim ws as Worksheet
B) Next in the Userform's Ok Button paste this code
Private Sub CommandButton1_Click()
ws.Cells(curcell + 1, 2) = shopkat.shopkatcombo.Value
Unload Me
End Sub
C) And lastly amend your above code to this
Sub Sample()
'
'~~> Rest of code
'
'~~> Change this as a applicable
Set ws = ThisWorkbook.Sheets("Sheet1")
For i = LBound(distshops) To UBound(distshops)
If Not IsEmpty(distshops(i)) Then
curcell = getrows
curshop = distshops(i)
findout = checkifinsheet(curshop)
If findout = False Then
ws.Cells(curcell + 1, 1) = curshop
shopkat.shop.Caption = curshop
'show form
shopkat.Show '<~~ No need to mention vbModal. It is default
End If
End If
Next i
'
'~~> Rest of code
'
End Sub