How I make excel show a await message while execute a macro? - excel

I have a macro that consulte to Database (in this case is a excel workbook), but when the macro consulte to database, it take 30 sec, and the user thinks that the program is broke. I tried with "Application.StatusBar = "Refresh File. "", but the user can´t see the sentence, the best way is a msgbox with the message "Await a moment", and, when the macro is finished, this message is closed. Do you help me with the code? I think the solution is this way:
Sub Button1_Click()
'Call msgbox with message "Await a moment"
Dim x As Long
For x = 0 To 2000000000 Step 1
Next
'The msgbox is closed
End Sub
I think the solution is a msgbox but it is a another option, Go Ahead!

A Msgbox wont work, because it would stop execution of everything until the user clicks OK.
The statusbar would work, if you put a DoEvents right after you set it so the system has a moment to update the screen.
Your only other option would be to create a special form that you show while it's processing, but you would also need a DoEvents after you show it as well.
Sub Test()
' create a userform and name it frmWait
' put whatever you want on that form
' that is what will be displayed while the user waits
frmWait.Show vbModeless
DoEvents
' do your processing here
Unload frmWait
End Sub
Or:
Sub Test()
Application.StatusBar = "Refreshing File. "
DoEvents
' do your processing here
' reset the status bar to normal
Application.StatusBar = ""
End Sub

Related

Sheet.activate not activating specified sheet

So I have officially run into a brick wall. I have written a macro that will allow the user, upon password entry, to unlock and unhide all sheets except for the one containing the password. At the end of the macro, I want to go to a specific sheet.
I have tried every reference to that sheet known to mankind, including both sheet code names and indexes, but the "sheet.activate" event just will not trigger. I have tried setting screen updating to true, both before and after the sheet.activate command. Events are enabled. I have disabled all Excel addins. I have tried everything I can possibly think of and everything I've found in forums all over the web. As you'll see from the code, I've even added basic time delays to the code at each step of the activating sequence, all to no avail. I've tried the activate sequence at different parts of the code. At the completion of the code, the best I get is activate the first sheet in my workbook. I even have Option Explicit enabled, and it sheds no light.
Now, the weird thing is, if I take everything out of the code except for the activate events, it works perfectly. If I step through the code line by line, the activate lines work. But if I compile the code and run the whole sub - nada. What the heck am I missing here?
Here is my complete code for this sub:
Option Explicit
Sub UnProtectAll()
Application.ScreenUpdating = False
Dim pPrompt As String
Dim bkPswrd As String
inputPass_box.Show
pPrompt = inputPass_box.passInput.Value
bkPswrd = Worksheets("Password List").Cells(3, 2)
If pPrompt = "" Then
MsgBox "You didn't enter anything...", vbInformation, "No password"
UnProtectAll
ElseIf pPrompt = bkPswrd Then
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Unprotect bkPswrd
Next ws
ThisWorkbook.Worksheets("Folder History").Visible = xlSheetVisible
ThisWorkbook.Worksheets("Master List").Visible = xlSheetVisible
ThisWorkbook.Worksheets("File Formats").Visible = xlSheetVisible
Unload inputPass_box
Worksheets("Change Sheet").Shapes("Button 1").Visible = False
Application.ScreenUpdating = True
Application.Wait (Now + TimeValue("0:00:03"))
ThisWorkbook.Worksheets("Folder History").Select
ThisWorkbook.Worksheets("Folder History").Activate
Application.Wait (Now + TimeValue("0:00:03"))
ThisWorkbook.Worksheets("Change Sheet").Select
ThisWorkbook.Worksheets("Change Sheet").Activate
Else
MsgBox "You have entered an incorrect password. Please check your password and try again.", vbCritical, "Wrong Password!"
UnProtectAll
End If
End Sub
Nevermind. I just figured it out, but here's my answer in case someone else needs help with the same issue. The line
Unload inputPass_box
was throwing it off for some reason ("inputPass_box" is a UserForm used as an input box). If someone would be so kind as to set me straight on this, I would be much obliged, but to my very limited knowledge, it seems that this line triggers the UserForm_QueryClose event, as in my project this event contains and "End" command to prevent the userform from passing any data back to the sub, as this would trigger several other events when I want closing or cancelling the user form to stop rather than displaying any of the error messages contained in the code block above.
pPrompt = InputBox("please input password")
bkPswrd = Worksheets("Password List").Cells(3, 2)
If pPrompt = "" Then
MsgBox "You didn't enter anything...", vbInformation, "No password"
UnProtectAll
ElseIf pPrompt = bkPswrd Then
use "InputBox" no problem,There may be a problem with the inputPass box

How to allow user to review worksheet using excel vba

My macro generates a series of reports that are 60 columns wide. I want users to be able to review the reports on screen before printing them or going on to another segment of the macro.
it there a way to set a scrollarea, have user review it, and then have the respond to a message box to continue the routine?
I tried this:
Sub reviewdata()
' Application.ScreenUpdating = False
Worksheets("Fin. Stmts").ScrollArea = ""
Application.Goto Reference:="monthlydata"
ActiveCell.Offset(2, 1).Select
ActiveWindow.FreezePanes = True
Worksheets("data. Stmts").ScrollArea = "monthlydata"
If MsgBox("End Review", vbOKOnly) = vbOK Then
End If
ActiveWindow.FreezePanes = False
Worksheets("data. Stmts").ScrollArea = ""
End Sub
the problem is that once the if, then statement is executed the user can not move around the worksheet since the routine needs a response to continue.
any insights are most appreciated.
thanks.
You can Use a Dummy Variable:
Dim dummy As Range
Set dummy = Application.InputBox("Scroll and Check. After That Select Ok!", "This is Specially created so that you can", Default:="A1", Type:=8)
Input Box that Takes in Range Allows you to Scroll in Background. Keep hitting Ok in and nothing will change, code will run as it is running at the moment.
This is a little clumsy but it sort of gets what you want. Instead of using a MsgBox use and InputBox as a range, which will allow the user to click around and scroll, as you describe. Whenever they hit okay/cancel, the macro will continue.
So probably replace your MsgBox line of code with....
Dim boom As Variant
boom = Application.InputBox("When you're done hit ""Cancel""... (""OK"" might lead to problems...)", _
"Scroll around and look at stuff", _
, , , , , 8)
I would recommend doing two macros instead, but this probably does what you need.
You can show that message in a small userform and call that userform in modeless state as shown below.
UserForm1.Show vbModeless
This way you will be able to navigate in the sheet with that message still showing.
You can also put the rest of the code in the button click event as shown below.
Option Explicit
Private Sub CommandButton1_Click()
ActiveWindow.FreezePanes = False
Worksheets("data. Stmts").ScrollArea = ""
Unload Me
End Sub

Msgbox not closing when WSH.Popup waits for certain time

I have an Excel file that opens automatically with Windows Scheduler. Also I have an Auto_Open sub to run a macro immediately. To avoid that every time it opens it starts running without a chance to modify it, I set up a msgbox that let me choose if the macro runs or not. However, I want Excel to automatically choose "Yes" after 10 seconds have passed, and I'm not able to get it. This is my code:
I have tried to place the seconds directly without a variable, I have also tried Case -1 alone, yet nothing works.
Sub Auto_Open()
Set WSH = CreateObject("WScript.Shell")
'cTime = 10
BtnCode = WSH.Popup("¿Desea generar la consulta de vacaciones?", cTime, "Consulta", vbYesNo)
Select Case BtnCode
Case vbYes
Call consulta
Case vbNo
Case 1, -1
Call consulta
End Select
End Sub
It might be easier to use a userform in combination with a module to run this. The UserForm would need to replace whatever you're doing with Msgbox. The code you'll need would look something like this:
USERFORM clode
Private Sub CommandButton2_Click()
'Run code for yes
'then
Unload Me
End Sub
Private Sub CommandButton1_Click()
'run code for "no".
'then
Unload Me
End Sub
Private Sub UserForm_Activate()
Application.OnTime Now + TimeValue("00:00:10"), "KeepItGoing"
End Sub
Then you can have it interact with an external module:
Sub launchSOMETHING()
'Run this first
UserForm1.Show
End Sub
Sub KeepItGoing()
If UserForm1.Visible = True Then
MsgBox "BOOOOMO"
Unload UserForm1
End If
End Sub
You can see an example in this file here.
UPDATED: It appears that all macros will pause while Msgbox is open. In the below two procedures, you'll note that the second one won't be triggered until after the box is closed, even though it was supposed to run in 5 seconds.
Sub TestWhatMsgBoxDoes()
Application.OnTime Now + TimeValue("00:00:5"), "someOtherMacro"
MsgBox "Everything is on hold?"
End Sub
Sub someOtherMacro()
Application.StatusBar = "The Second Macro has run at" & Now()
End Sub
I think has to do with the "Call consulta" procedure, try use megbox to test it.
Ok, so after a lot of research I managed to do what I want without a lot of issues.
First, I created a scrip (.vbs file) that contains the following:
Dim objExcel
Dim objWB
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWB = objExcel.Workbooks.Open("R:path\file.xlsm")
objExcel.Run "MyMacroName"
objWB.Save
objWB.Close False
objExcel.Quit
Now every time I run the script, the macro would run automatically. I have also set up a Windows Scheduler Event so it will run by itself with the script. In that way, I don't need a Popup to ask me if I want to run something, and the script would only run when the Event is triggered by the conditions set.
On the other hand, the Excel file itself is free from autorun when the workbook is opened, so any user can modify it without any problem.
Thanks to the people that helped me through this.

Excel error, stops running macro

I am experiencing an odd bug on Excel. I have a macro that shows a non-modal userform when I press CTRL+m (Macro shortcut). Every once in a while, and it's not that frequent (Shows up once or twice during the day, I use the macro every 5 minutes or so), Excel won't run the macro, won't show the userform and will just beep (as in "mistake, cannot proceed executing code").
I went into the Macro window to try to press "Run" and manually execute, but all buttons are disabled, except for "Create". If you click it, it says the macro name is not valid. As you can see in the screenshot below, the name of the macro shows the instance where the code is (Sheet1 of the workbook).
Sometimes it can be fixed by saving the workbook and just re-trying, but sometimes it doesn't; when it doesn't, I run a different macro (by double clicking a specific column) that shows a modal userform, and executing its code. Then my first macro returns to normal.
Any help will be very much appreciated.
Edit: Adding the code as requested in the comments
Sub ShowCommentWindow()
Dim myCell As Range
Dim companyColumn As Long
Dim wbk as Workbook
Dim company as String
Dim phone as Long
Set wbk = ActiveWorkbook
For Each myCell In wbk.Worksheets(1).Range("A1:Q1")
If myCell.Text = "Company" Then
companyColumn = myCell.Column
company = ActiveCell.Text
phone = ActiveCell.Offset(0, 4).Value
Exit For
End If
Next myCell
If ActiveCell.Column = companyColumn Then
If EmailForm.Visible Then
GoTo ExitProc
Else
If Not ActiveCell.Row < 4 Then
ActiveWindow.ScrollRow = ActiveCell.Row - 3
Else
ActiveWindow.ScrollRow = ActiveCell.Row
End If
If CommentWindow.Visible Then
CommentWindow.AddButton.SetFocus
CommentWindow.CommentBox.SetFocus
Exit Sub
Else
CommentWindow.Show
ManageComments
AddComment
End If
End If
End If
ExitProc:
End Sub
Edit2: Posting more code, for QueryClose:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Dim myCell As Range
Dim isCompany As String
If Not CommentWindow.CommentBox.Text = CommentWindow.TextCopy.Text Then
saveConf = MsgBox("Changes have not been saved yet. Do you want to save?", vbExclamation + vbYesNoCancel + vbDefaultButton2, "Save changes?")
If saveConf = vbYes Then
Call SaveComment
GoTo ExitProc
ElseIf saveConf = vbCancel Then
changed = True
Cancel = 1
CommentWindow.AddButton.SetFocus
CommentWindow.CommentBox.SetFocus
'CommentWindow.CommentBox.Text = CommentWindow.TextCopy.Text
Else
CommentWindow.TextCopy.Text = CommentWindow.CommentBox.Text
GoTo ExitProc
End If
Else
If Not changed = True Then
GoTo ExitProc
End If
End If
ExitProc:
End Sub
Seems like the issue is not unloading the forms from ( Unload(UserForm) )
This leads to a memory leak.
Even the official documentation -this refers to Access, but, should behave the same for Excel (there's no Form object or userform documentation there)- state the Lifecycle is Unload->Deactivate->Close, and this should happen when you close the userform as well, daily usage has shown that Unload if not stated may not be triggered when closing the userform.
The lifecycle is not that strictly monitored sometimes, but, that may lead to memory leaks and strange behaviors, always when working with objects you shouldn't rely that garbage collector will clean them if not specified. Probably adding something to confirm that terminate is being correctly handled will be helpful.
EDIT
If you're having problems remembering the unload -or still having problems with memory-, it will be a good practice to do the following:
Sub MyMainProcess()
Dim myform As UserForm1: Set myform = UserForm1 'this is your UserForm name
myform.Show
'my stuff needed...
Unload myform
Set myform = Nothing
End Sub
Unload and Nothing to clean as much as possible with coding
I see that you're calling an "outside" macro (it's not within the active workbook) - Is it possible that then those roughly 2 times a day that it doesn't work that workbook (Database 2 Lumber.xlsm) is being used by someone else at that time (eight running that, or another macro?).
If so, What I have done before is save a local copy of the workbook each time the macro is run

Pause a Macro, Edit sheet, and Resume without buttons

I have a macro that needs to be run for many workbooks. There is a part though where I update a segment of the connection string with unique values and apparently this can't be done in VBA so I must manually do it. Is there a way I can have the Macro do what it does then pause while I update the connection string for say 30 seconds then start running again to completion?
Thanks,
Here is a macro that will allow you 30 seconds to make changes and then resume operation:
Sub dural()
'first part
'do stuff
MsgBox "Perform updates"
t1 = Now
While Now < t1 + TimeSerial(0, 0, 30)
DoEvents
Wend
MsgBox "Resuming the second part of the macro"
'macro does more stuff
End Sub
NOTE:
the DoEvents allows focus to be shared with the user.

Resources