Macro Fails, 'The macro may not be available in this...' - vba

Hello and thank you in advance for your assistance.
I have some code that I admittedly borrowed from a site. It changes the sheet that is being displayed every X seconds. In my case 3 seconds. When I run it it will change to the next sheet one time and then error out after the 3 seconds.
The error I receive is "Cannot run the macro "C:\users\BenjaminSmith\Desktop\Book1.xlsm'!displaysheets'. The Macro may not be available in this workbook or all macros may be disabled."
Here is the code for my Macro
Sub displaysheets()
ShtNum = ActiveSheet.Index
ShtNum = ShtNum + 1
If ShtNum > Sheets.Count Then
ShtNum = 1
End If
Sheets(ShtNum).Activate
Application.OnTime Now + TimeValue("00:00:03"), "displaysheets"
End Sub
If I remove the line
Application.OnTime Now + TimeValue("00:00:03"), "displaysheets"
I can run the macro over and over and there are no issues. Other than the fact it doesn't continue on its own...
The spreadsheet is an XLSM.
MS VBA is 7.0.
Excel is 2010.
I am thinking maybe the issue is because the code is recursive?
Thanks for your suggestions.

Further from the comments...
The code didn't work because you didn't paste the code in a module. This is a very common mistake among new programmers. In such a case, Excel is unable to find the code as it searches the module.
#Siddharth Rout I had the code in 'ThisWorkbook' I inserted a module 'Module1' and moved the code there and everything works as expected. What is the difference with these two places?
I would recommend going through Chip Pearson's link HERE
Extract from the link if the link ever rots.
Standard Code Modules, also called simply Code Modules or just
Modules, are where you put most of your VBA code. Your basic macros
and your custom function (User Defined Functions) should be in these
modules. For the novice programmer, all your code will be in standard
modules. In addition to your basic procedures, the code modules
should contain any Declare statements to external functions (Windows
APIs or other DLLs), and custom Data Structures defined with the Type
statement.
Your workbook's VBA Project can contain as many standard code modules
as you want. This makes it easy to split your procedure into
different modules for organization and ease of maintenance. For
example, you could put all your database procedures in a module named
DataBase, and all your mathematical procedures in another module
called Math. As long as a procedure isn't declared with the Private
keyword, or the module isn't marked as private, you can call any
procedure in any module from any other module without doing anything
special.
Workbook And Sheet Modules are special modules tied directly to the
Workbook object and to each Sheet object. The module for the
workbook is called ThisWorkbook, and each Sheet module has the same
name as the sheet that it is part of. These modules should contain
the event procedures for the object, and that's all. If you put the
event procedures in a standard code module, Excel won't find them, so
they won't be executed. And if you put ordinary procedures in a
workbook or sheet module, you won't be able to call them without fully
qualifying the reference.
User Form Modules are part of the UserForm object, and contain the
event procedures for the controls on that form. For example, the
Click event for a command button on a UserForm is stored in that
UserForm's code module. Like workbook and sheet modules, you should
put only event procedures for the UserForm controls in this module.
Class Modules are used to create new objects. Class modules aren't
discussed here, except to say that a class module is used to handle
Application Event Procedures.

Try : (i use this code)
With Application
.EnableEvents = True 'needed
.OnTime EarliestTime:=Now + TimeSerial(0, 0, 3), Procedure:="displaysheets", Schedule:=True
End With

Try to put your timer in a global variable and add it each time you run the function, also configure OnTime to be schedulable
Global tmrTimer1
Sub displaysheets()
tmrTimer1 = Now + TimeValue("00:00:03")
'Enable the schedule
Application.OnTime tmrTimer1 , "displaysheets", , True
End Sub

Related

Cannot run the macro. The macro may not be availabe in this workbook

Having an issue with VBA error 'run time 1004'. Using the following code. The macro is called from a button in Row 5, hence the subtraction. There are other buttons in rows 6, 7, 8 etc. all calling the same macro (to subsequently call a specific userform), hence the variable.
Sub Export()
i = RowNumber - 4
Reinstated = "ReinstateR" & i
Application.Run Reinstated
End Sub
The macros 'ReinstateR1', 'ReinstateR2' etc. are all stored in a separate module.
Sub ReinstateR1()
'Macro function etc.
End Sub
For some reason, though, when I click the button, I get the following error message:
"Cannot run the macro 'ReinstateR1'. The macro may not be available in this workbook or all macros may be disabled."
All macros are enabled, the macro is in the same workbook, etc. Trust centre settings are set to disable all macros with notification, etc.
I'm stumped. I can call the macro without the variable, but that's not the point...
If you have a module with the same name as a routine it contains, you need to prefix any call to it using Application.Run with the module name as well (or change the name of either the module or the routine), so in this case it's:
Application.Run "Reinstater1." & Reinstated

transferring variable form one workbook to another workbook vba

I am creating a userform (userform1) in workbookA and in the userform, I'll be needing a module(module1) created in other workbook (workbookB) to made some calculation. In order to launch the calculation, the module need some info (TTAA, tolerance). I would really love to know the easiest way to transfer some variable from userform1(workbookA.userform1) to module1(workbookB.module1) and re-transfer the results to userform1.
below, you can find a small part of the programm which I've coded to call the module.
TTAA = CDbl(Me.TTAA_textbox.Value)
tolerance = CDbl(Me.tolerance_textbox.Value)
application.Run ("'Workbooks.xls'!module1")
I've declared as public, the variable TTAA and tolerance in the module1
The easiest way (which I know to work) is to temporarily "save" the variable on a sheet in one of either file and then reference it as
Worksheets.Add.Name = "tmp"
Workbooks(WorkbookA.Name).Worksheets("tmp").Range("A1").Value2
'And remove it later on
Application.DisplayAlerts = False
Workbooks(WorkbookA.Name).Worksheets("tmp").Delete
Application.DisplayAlerts = True
An alternative might be to declare the subs in WorkbookB as functions. Apart from public variables this is the only way to get return values (in a native format) from independent VBA code segments. Yet, if you had no luck with public variables I doubt this will work.
But why don't you import the module into WorkbookA instead? The following SO answer might be able to help you with that.
Writing a macro that writes a macro to another Excel-file

What's the difference between module and a module sheet?

I have three modules (standard module, not class module) in my Excel VBA project. One of those was added by right-clicking the VBAProject and insert a module. Two of them were added by executing "modules.add"; I guess modules means module sheets, right? So, my questions are:
1. What does a module mean in VBA?
2. How can I know which module is created while adding a modulesheet?
3. Why when I add a worksheet,there isn't a module appear?
A module is simply a place to put your code. You can just see it as a sheet of paper where you can write something.
In Excel you can put your code in a module, or "behind" a worksheet (what you call a modulesheet). A module is always added manually BY YOU. The "modulesheet" is part of a sheet and thus added or deleted BY EXCEL automatically whenever you create or remove a sheet
When you put some code and variables in a module, its instantly available from all worksheets within your workbook, dependinv on how you declare your variables, subs and functions (private/public)
Usually when one put code behind a worksheet, its because this code is only meant to be called from that particular worksheet and only perform operations on it. I personnaly never work on worksheet level for several reasons:
if you delete your sheet, you lose all code that was behind it.
if you export a sheet, you export the code as well.
if you duplicate a sheet, you duplicate the code as well.
if you want to run the code behind a particular worksheet from another place, you have to fully qualify your calls and variables, which is a horrid solution and also plain boring
My advice is: IN EXCEL, never work on sheet level, uses modules, and if you reach a decent amount of code, organise it in logical groups using multiple modules
RE 1: A module is like a singleton class which has already been initialized, so to speak. In other words a module's code (public properties/variables, public methods, etc) is always available, one does not have to inherit an instance before tries to use it, however, all the data in a module's properties/variables are common "application-wide"
RE 2: It is "sheet module", not "module sheet". This means nothing but the newly added sheet has a module with it when you add it. There's no difference between having this, or adding a module to the sheet later. You can open the code editor window and see modules, classes, etc by pressing ALT+F11
RE 3: By default no VBA code is added to any new sheet because of security reasons. If a Workbook has macro (VBA code) in it, extra attention is required so by default a workbook is not a VBA(macro) workbook.Last but not least, please note that there's no difference between one module or another. The way you create a module does not affect the way modules behave, and there's only one "type of module" (as well as one "type of class module") in Office applications (Excel, Word, etc)
for number 2:
Sub moduleAdd()
Modules.Add
'Modules.Add
qq = Modules.Count
MsgBox "total added module by code = " & qq
For ii = 1 To qq
Set modu = Modules(ii)
If ii = qq Then MsgBox "Newly added module = " & modu.Name
Next
End Sub

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.

make excel files use a global workbook function with vba?

I am new to vba and I have problem understanding the workbooks in vba for excel files.
I have a macro called Addin.xla, this macro is used by 2000 files.
The problem that I have, is that the 2000 files have its own thisworkbook thats declares the function Workbook_BeforeClose. All the 2000 files have the exact same Workbook_BeforeClose.
What I want to do is to change the Workbook_BeforeClose function in all the 2000 files. Can I make the files use the Workbook_BeforeClose function in the Addin.xla file or must I change the same Workbook_BeforeClose function for all 2000 files?
If the later is the case, can someone show me how to write a macro that loops through all the files and updates this function automatic?
In the addin, handle the Application.WorkbookBeforeClose event.
But if you already have same code in 2000 files, you will have to remove it anyway. Otherwise it will run in addition to the handler you will define in the addin.
To auto remove:
Add a reference to Microsoft Visual Basic for Applications Extensibility X.X.
Then open each file in a loop and do
With currentWorkBook.VBProject.VBComponents("ThisWorkbook").CodeModule
.DeleteLines .ProcStartLine("Workbook_BeforeClose", vbext_pk_Proc), .ProcCountLines("Workbook_BeforeClose", vbext_pk_Proc)
End With
One solution would be to delegate the function to the addin:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
runCleanupCode
End Sub
where runCleanupCode is located in your addin. That means that if you want to make changes in the future, you only need to make them in the addin.
To change the code in all your sheets, you can follow this example.