I am automating testcases for my company's addin.
In one of the testcases, after saving my workbook on my local machine when I try closing the workbook, I am required to click on 'Yes'- saves edited data in our database, 'No'- discards the edits or 'cancel'- simply closes the message box.
I have tried using sendKeys but that didn't work for me.
Eg: For clicking 'No' through my VBA code, I tried to send tab and enter keys like this:
Application.Wait (Now() + TimeValue("00:00:10"))
Call SendKeys("{TAB}", True)
Call SendKeys("{ENTER}", True)
I have tried with various time values still didn't get any success. I would be glad if someone can help me with this.
Thanks in advance! :)
UPDATE: As of now, I have been doing this:
'Some tasks...
ActiveWorkbook.Save
Call Application.Run("workbook.xlsm!Discard")
Application.DisplayAlerts = False
ActiveWorkbook.Close SaveChanges:=False
Application.DisplayAlerts = True
But is there any way to get the window object reference for the message box? Or anyway to stick to the workflow: edit workbook -> save -> try closing -> opt to discard/commit changes to database?
NOTE: By discarding/committing changes to database, what I mean is a server where the data gets updated. Excel is just an interface for the user. I don't want just the excel to be saved but the operation of calling discard/save changes on server as well...
if you have already saved the workbook, you only need to close the workbook. Please try the below code
Activeworkbook.close false
This will close your workbook and you wont be promted for selecting any options.
Related
I realize this question has been asked before, but the supplied answers did not solve the problem. I'm running VBA code from within Excel which does the following:
1.) Open a local worksheet (i.e. C:\desktop\AOR\Names.xlsx)
2.) Read down column B getting the names of files that need to be verified
3.) Open the filename (as taken from column B) from a Network drive.
4.) Verify some cells from the opened file
5.) Close the file.
6.) Iterate.
All this is working with no problems; my situation is that when the file is opened from the Network drive (i.e. step 3) I get the "Downloading File" message. The only option on this is "Cancel" or let it go to completion. Pressing cancel (or using SendKeys to do so) causes the file open to cancel, thus stopping the rest of the process. I've had users accidentally press this cancel enough times that I want to suppress the dialog box completely but cannot find anything that works.
Here is some code with the options I've tried all to no avail:
WhatName = Workbooks(AgencyNamesList).Worksheets("Agencies").Range("B" & i).Value ' get name of file from locally opened workbook.
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Application.EnableEvents = False ' Prevent code in workbook from running
' Application.SendKeys "{ESCAPE}", False ' Cancels subsequent file opens
' Application.SendKeys "{ESCAPE}", True ' Cancels the file open
' Application.SendKeys "~", True ' Cancels the file open
QuarterDueDate = Workbooks.Open(SourceFolder & WhatName).Worksheets("YTD").Range("I6").Value ' open book get value of I6
This page shows a picture of the dialog box along with someone else trying to find a solution (since 2012) to this problem.
OPSYS: Windows 7 Enterprise SP1
EXCEL: MS Office Professional Plus 2013
I'm sure hoping someone has found a way to prevent this pop-up box from popping!
NOTE: When this code is run against the same files stored locally, the dialog box does NOT display.
Thanks!
I have an excel workbook that I download using simple HTML portal that I coded. When I download the workbook it automatically renames it as "myWorkbook (27)" or whatever number of times it has been put in the downloads folder.
I have some code that changes the Save As location of the workbook to the original location that it was downloaded from. See:
Private Sub Workbook_Open()
Application.DisplayAlerts = False
'Check to see if another workbook with the same name is open -- close if so.
If IsOpenWorkbook("myWorkbook.xlsm", True) Then
Workbooks("myWorkbook.xlsm").Close saveChanges = False
End If
ThisWorkbook.SaveAs Filename:="\\999.9.9.99\folder\anotherFolder\myWorkbook.xlsm"
Application.DisplayAlerts = True
End Sub
This has worked fine for almost a month but recently has been performing erratically. When I first download the sheet, it has the regular "Enable Editing" prompt which I accept. After accepting, the name of the workbook changes suggesting the code as run, but then has another "Enable Editing" prompt which, if I accept, will crash Excel.
Any insights appreciated.
I am writing a macro in VB in excel 2013. The only remaining bug left is when the macro runs, all of the other workbooks i have open close, even ones unrelated to the macro. I do not want users of my macro to lose other tabs of excel they may have open if they run my program. I have tried using "Application.Visible = true" but it is not giving me the desired behavior. Is there a way to run a macro without affecting any other currently open workbooks? Or is it possible that something else I have written is overriding the Application.Visible method? If someone could provide a recommendation it would be much appreciated.
Application.Visible = false
Simply does what it says, set the application "Excel in your case" to invisible.
If you want to hide something specific you have to call this:
e.g Sheet
Sheets("Whatever").Visible = False
e.g Workbook
ActiveWorkbook.Windows(1).Visible = False
//ActiveWorkbook needs to have an reference to the specified Workbook which you get as an example if you store the opening of the workbook (ActiveWorkbook = Workbooks.Open )
It sounds like you have a line
Workbooks.close
(which will close all workbooks) when what you wanted to do was close the specific workbook with the macro. That should be
ThisWorkbook.Close
Have Excel (2010 in my case but I think it will be the same also in other versions) with two workbooks. Save first one with name "1.xlx" (example) via Save As dialog. Save second one with the same name "1.xlx" to different location. Excel will not allow it with following warning message:
"You cannot save this workbook with the same name as another open workbook or add-in. Choose a different name, or close the other workbook or add-in before saving."
So far so good. But my problem is that I need to invoke dialog via VBA. I am using following code:
Sub test()
Application.Dialogs(XlBuiltInDialog.xlDialogSaveAs).Show
End Sub
Now I am trying to save second workbook (with the same name to different location) but when I click to 'Save' button nothing happen, no warning message. If I wouldn't know what is wrong it would be very difficult to tell. I didn't change any setting (there is nothing as DisplayAlerts set to true or so). Any idea how make SaveAs dialog invoked via VBA to display similar warnings?
I'm not sure why that doesn't give you an error, but it doesn't me either. If you use Application.FileDialog, you can get that error.
Sub testts()
With Application.FileDialog(msoFileDialogSaveAs)
.Show
.Execute
End With
End Sub
Or you could use GetSaveAsFileName and check the names of all the open workbooks and generate the error yourself.
Can you try with the below code on starting on your code.
Application.DisplayAlerts = True
I've spent the last two days working on this problem. Most of the content I've found on this topic doesn't address the issue I'm having, so I'm hopeful that someone here can help me.
I've been working on some code that does the following from a "master scorecard" workbook:
Takes each "student" sheet in the workbook and copies the sheet into a new workbook,
Does a few minor manipulations of the new workbook,
Imports a module of code into the new workbook,
Adds a Workbook_Open event and a Workbook_BeforeClose event to the new workbook (to make certain sheets xlVeryHidden depending on level of access),
Runs a subprocedure from the newly imported module,
Saves and closes the workbook.
Each scorecard uses code to ensure that only the person whose name is on the scorecard can access it. I've used Environ("username") in the workbook events to ensure security, but as you well know, if one and understands how to run macros, he/she could merely open the VBEditor and unhide the xlVeryHidden sheets in the workbook very easily.
So, my thought was to password protect the new workbook's VBAProject programmatically (see above: step number five). I found a few sources online of how to use SendKeys to achieve this goal (see below), but SendKeys is unreliable (at best) and isn't cooperating with my code. The code works like a charm if I run it by itself, but if I call it from another project using Run Macro:="filename!macroname" it doesn't set the protection. After the code has run and all the workbooks have been created, the VBAProject properties window(s) from the earlier code are all open and try to execute at the same time which crashes Excel.
Sub LockVBAProject()
Const VBAProjectPassword As String = "123"
Dim VBP As VBProject, openWin As VBIDE.Window
Dim wbActive As Workbook
Dim i As Integer
Set wbActive = ActiveWorkbook
Set VBP = wbActive.VBProject
Application.ScreenUpdating = False
' close any code windows to ensure we hit the right project
For Each openWin In VBP.VBE.Windows
If InStr(openWin.Caption, "(") > 0 Then openWin.Close
Next openWin
wbActive.Activate
With Application
'//execute the controls to lock the project\\
.VBE.CommandBars("Menu Bar").Controls("Tools") _
.Controls("VBAProject Properties...").Execute
'//activate 'protection'\\
.SendKeys "^{TAB}"
'//CAUTION: this either checks OR UNchecks the\\
'//"Lock Project for Viewing" checkbox, if it's already\\
'//been locked for viewing, then this will UNlock it\\
.SendKeys "{ }"
'//enter password\\
.SendKeys "{TAB}" & VBAProjectPassword
'//confirm password\\
.SendKeys "{TAB}" & VBAProjectPassword
'//scroll down to OK key\\
.SendKeys "{TAB}"
'//click OK key\\
.SendKeys "{ENTER}"
'the project is now locked - this takes effect
'the very next time the book's opened...
End With
ThisWorkbook.SaveAs Filename:=Sheets(Sheets.Count).Name, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Debug.Print "It Worked " & Now()
End Sub
I'm not sure why this is happening; like I said, the code works fine when run on its own. I found this post where this link to a non-SendKeys approach was outlined, but it was written several years ago and I'm not sure how I'd need to modify it for my purposes since I've never coded in VB6...
Are there any thoughts as to why the SendKeys method is bunching up after the code has already run instead of executing when it's supposed to during the code? Should I abandon SendKeys in favor of this other method? I'm at a loss, so any help will be much appreciated!
EDIT: I think the reason the code isn't working is because the correct project isn't activated at the time the SendKeys code is executed. I had hoped that activating the proper workbook would solve the issue, but it doesn't appear to have helped.
Ok, so after another couple of hours of searching the web for alternative methods to achieve my goal, I stumbled across this post.
I created a template workbook (with the event code already in ThisWorkbook), password protected the project, and modified my code to use the template workbook for each new sheet. Now when the sheets are created, the project is already locked for viewing and requires a password. While I realize the security under this approach isn't very secure, it will help "keep honest people honest" as they say.
For those who stumble across this post and still wish to programmatically lock/unlock their VBA Project, see these resources:
This SO post
This blog
Both are great resources that walk through a way to do it in VBA.
To add a nuance to the otherwise fine piece of code originally posted here: If you change the Project Name for the workbook within the VBE, you'll need to change one line of code to:
.VBE.CommandBars("Menu Bar").Controls("Tools") _
.Controls(VBP.Name & " Properties...").Execute
(sigh)