Unhide, unprotect and run macro from another spreadsheet - vba

I am currently teaching myself VBA. I work with Excel 2010 a lot but only know the basics of VBA.
To help teach myself, I have set a project for myself which is to create a dashboard in Excel where I can click a button and it opens three reports I run each morning at work and runs a macro on each. The process of each report is to
1 - open report
2 - unhide worksheet (worksheet = "Control Sheet")
4 - run macro on the unhidden sheet (macro = "ButtonClick")
5 - hide worksheet
5 - Save and close report
I have managed to get 1 report to open using:
Sub EasierRun()
Dim Location As String
Location = "location/filename.xlsm"
Workbooks.Open(Location).RunAutoMacros (xlAutoOpen)
End Sub
I copied the 2nd to last line from the internet but it doesn't run any macro, it just opens the file. No error messages display. I understand that I need to be specific about the worksheet and macro I want to work with but I'm not sure how to proceed from here. Also, I'm not sure if I need to tell it to unhide the worksheet in the VBA? Finally, would I need to write individual code for each report to open or do I declare the files all at once and then the remainder of the code works universally?
I've googled and read a lot but I can't manage to adapt what I am finding to fit what I need.
Thanks for any guidance.

Unfortunately, for security purposes, you can't force a workbook to enable macros without explicit input from the user.

Related

VBA Ribbon Bar Integration

I have an Excel macro that performs a few functions on a document (Creates as form, and a few emails) all from MS-Word documents. If the macro is executed from the main spreadsheet (where the macro is), everything works normally. I want to place this macro on the ribbon allowing a user to launch it without having (or knowing where the main excel document is located or having it open). I created a sub to check to see if the spreadsheet was open and modified the ribbon to include an icon for the macro.
Which works. However, when launched from the ribbon while the main Excel spreadsheet is not open, it opens the workbook and runs the macro in entirety (Without executing the open workbook line of the macro). I assume the spreadsheet is being open because the macro that is being called resides with it (makes sense). Since the macro is dependent on the data contains in the spreadsheet, I need to allow the users to modify it and then re-running the macros from the ribbon again.
Does anyone have a recommended approach or best practices? Thank you in advance.
Sub MainForm()
Dim WorkingFolder As String
Dim File01 As String 'Main Excel Data File, where all data is
Dim File02 As String 'Preliminary Email to send to user
Dim File03 As String 'Final Email to Send to user when production is complete
Dim wb As Workbook
WorkingFolder = "C:\Temp\"
File01 = "01-MainData.xlsm"
File02 = "02-PreProductionEmail.docx"
File03 = "03-FinalProductionEmail.docx"
If wbIsOpen(File01) = True Then
MsgBox "Workbook Is Open"
Run ("'C:\Users\Guest\Nextcloud\Documents\Excel Forms\02-TEST-Production Request-Data.xlsm'!CreateProductionForm")
Else
MsgBox "The Main Datafile is not open, verify the last row before re-runing", vbOKOnly, "Not Open"
Set wk = Workbooks.Open(WorkingFolder & DataFile)
End If
End Sub
The Guide mentioned by Ricardo was not quite what I needed but it was helpful and did put me on the right track. Thank you again Ricardo. To get this working, I needed to do the following.
1 - Make the procedure above its own separate *.xlam file (saved as an add-in).
2 - Add the add-in to start automatically via the developers tab
3 - Add the Macro to the Ribbon.
I have modified the sample above to included the open statement along with the statement that executes a macros from another workbook.
Appreciate the guidance.

Run Macro from Desktop Shortcut

I wrote a macro that does some calculations based on a particular type of excel sheet. Im trying to distribute this to my coworkers but the addition of a macro to a workbook and then running the macro is something foreign to them. I'd like to have a "shortcut" or some VBS program to open a specific workbook (specified by the user), run the macro, and display the results.
Your help is appreciated!
--Edit--
I wrote a macro in VBA. I exported the file to my desktop. Its simply called "Macro1". We have a standard form of excel sheet our company uses. Its literally the same sheet with different numbers. The macro I designed works on these kinds of sheets and does calculations. My coworkers aren't good with macros, so I want some sort of "code" that will prompt one of my coworkers for an excel file, then execute the macro on the file. Hopefully this clarifies any questions.
You need to make it a excel add-in.
Then in the add-in make it run on workbook open with Sub App_SheetActivate(ByVal Sh As Object) in thisworkbook.
In the macro you can then have it only activate on certain workbook name or workbook type by:
If range("A1").value = "something" ' something that makes the workbook type special.
' Maybe you need B1 value and so on too.
Do you need a way to self-install the add in just let me know and I have a code for that too.
Self install:
' if add-in is not installed and the workbook is a add-in (workbookcount =0)
' Also take note that this code will only run if the add-in is not installed
If Dir(Application.UserLibraryPath & "YourWorkbookName.xlam") = "" And Workbooks.Count = 0 Then
'optional ask user if he wants to install or not. Code not included.
' copy file from current position to add-ins folder.
Result = apiCopyFile(ThisWorkbook.FullName, Application.UserLibraryPath & "YourWorkbookName.xlam", False)
' activate the add-in
AddIns("YourAdd-inName").Installed = True
msgbox("add-in installed")
' Close Excel since add-ins does not work without restart of Excel
On Error Resume Next
Application.Interactive = False
AppActivate "Microsoft Excel"
Application.Quit
Exit Sub
End If
Note that the file must be saved as a add-in. (xlam) this means there is no sheets, the workbook is VBA code only.
Normally, that does not mean the code needs to be written in a special way.
Usually Range("XX").value works, but some commands may need to point towards the correct workbook. (you have two workbooks open with add-ins, the add-in with the code and the workbook with the sheets and numbers)
Hope this helps

Excel Quirk - Tab stops working when protect another sheet

I just came across a quirk and have no clue why this is happening - I'm using Excel 2010 and have the following situation:
I have 2 sheets - An "input" sheet and a "save" sheet
Save sheet is protected; input sheet is not
I have a VBA Macro that un-protects the save sheet, copies the data across between the 2, then re-protects it
When this macro runs, the input sheet (which was never protected) now has the tab key not working (cannot tab between cells).
To replicate this situation easily, I created a new blank workbook and did the following:
Password protected Sheet2 with the password "Test"
Put in the following simplistic VBA sub:
Sub WeirdQuirk()
Sheets("Sheet2").Unprotect Password:="Test"
Sheets("Sheet1").Range("A1").Copy Sheets("Sheet2").Range("B1")
Sheets("Sheet2").Protect Password:="Test"
End Sub
When I'm in Sheet1 and run this, afterwards the Tab key is no longer working in the sheet.
Any thoughts on why this is happening / how to fix it?
FYI, I did come up with a fix, but it's not what should be done - Hopefully someone else has a better solution that I'll accept, but I do want to post this in case anyone else gets stuck in this situation...
What I ended up putting in to re-enable the tab key was adding in the line of code:
Application.TransitionNavigKeys = False
OR:
Application.TransitionNavigKeys = True
if you want that feature enabled.
Hope it helps other people.

VBA macro crashing Excel 2010

I have an Excel 2010 spreadsheet that I use to maintain tests for an automated test application written with Selenium WebDriver. The spreadsheet has 6 ActiveX buttons that Upload (to a database), Import (from another sheet), Clear All Sheets, Export (to another sheet), Merge (two sheets), and Restore (a test suite from the database). My problem seem to stem from the macro that runs when the Import button is selected
The macro takes two sheets, source and destination, clears the destination sheet and copies the cells and data from the source workbook to the corresponding sheet in the destination workbook. From there, it can either be uploaded to the database or run from the sheet by the testing app
A couple weeks ago when selecting the Import button Excel crashed. I looked on the web and found a solution that worked. It involved disabling all macros, shutting down trust documents and trusted locations, recompiling, and reopening the workbook. This worked for a couple weeks until the same thing happened again this past weekend and the fix did not work anymore.
Here is the code I have:
numSheets = wrkBook.Sheets.Count
appName = wrkSheet.Cells(2, 3).Value
bkPath = Application.GetOpenFilename("Excel Macro-Enabled Workbook (*.xlsm),*.xlsm")
If bkPath <> "False" Then
Call Clear_All(wrkBook, wrkSheet)
'get the number of sheets in the source workbook
destCnt = wrkBook.Sheets.Count
Set importBook = Workbooks.Open(bkPath)
For a = 1 To destCnt
thsShtName = wrkBook.Worksheets(a).Name
'activate the source workbook
importBook.Activate
'get the numer of sheets in the source workbook
srcCnt = importBook.Sheets.Count
'loop through each sheet checking title
For b = 1 To srcCnt
'get the name of the 'a' sheet
**srcSheetName = importBook.Worksheets(b).Name**
'do more stuff with the source sheet
Next b
Next a
End If
The code is crashing on the following line
srcSheetName = importBook.Worksheets(b).Name
Here are a few things that I have noticed. Once the importBook variable is set, I cannot expand the variable in a watch window even if the code has not reached the offending line. However, the macro will successfully get the srcCount (number of sheet on the source sheet). Once the macro gets to the offending line it crashes consistently with a message stating simply that Excel has encountered an error and needs to close . No information, Excel closes, and sometimes restarts to a blank workbook
OK...I figured this out myself after heeding Siddarth Rout's suggestion about a corrupt spreadsheet. I took the steps that I described above
So here's what I did.
I copied one of the other spreadsheets and cleared it. As soon as I ran the Import macro, it passed through the line where it was failing before, so a corruption seems to have been the issue. I then stepped through the original code and rewrote the Import macro to simplify the code in it. It now seems to be working just fine
Thanks for the suggestions!!

Where Exactly To Store VBA

We receive Excel files daily from our field offices which I have to clean and re-format (about 110 columns and 500 rows-worth) using VBA.
I need to save my VBA as a macro so we can use it to clean up all the workbook we receive by running the macro and saving the edited sheet as a new worksheet by getting the name from UserForm Combobox items.
Where exactly should I store the VBA snippets? I mean when I open the Visual Basic panel, I have these three options:
Running The Code From Microsoft Excel Object :Sheets1(Sheet1)
Running the Code From An Inserted Module
Running the Code From User Form
If I am supposed to use options 1 or 2, how can I call the UserForm for saving the sheet?
I Recomend you to use modules (Option B)
Option C goes with option B, ill explain, you can create a sub in a module in option B, then you can do:
UserForm1.show
In Option B I would writte this code, but before trying this i recomend you to understand a bit more of vba
sub ClearWBs()
'opening workbook
Workbooks.Open Filename:="c:\book1.xls"
'your code
'your code
'below code for saving and closing the workbook
Workbooks("book1.xls").Activate
ActiveWorkbook.Save
ActiveWorkbook.Close
end sub
Use Module:
If your VBA code focusses on data summarization and manipulation I suggest you use a Module.(example is what you have described in your question).
Use Form:
If what you wan't to do requires a GUI(Graphical User Interface) then you'll have to resort to Form where you can design your GUI. (example is if you have many fields that the user needs to fill-up with distinct values in which you provide the choices)
Use Excel Object:
If what you wan't to do has something to do with events happening on Worksheet and/or Workbook, like for example whenever you add sheet the macro runs, or when you open or close the workbook the macro runs then you will have to write the macro in the Excel Object.
This is basically what i have in mind, hope this helps.
If you receive files that do not contain VBA and you need to apply the same code on those files all the time then I propose that you either save that code in your personal workbook.
You can see how to do that here: http://office.microsoft.com/en-ca/excel-help/copy-your-macros-to-a-personal-macro-workbook-HA102174076.aspx
This is nice because you can also tie it to keyboard shortcut or just have it always ready for you to use.
The disadvantage is that it will only be set up per user session per computer. What you can do is have that code all set up in a module and then import it into your personal workbook if you change session or if someone else has to do it.
Once it's done, you will not have to include the module in your files your receive again.