Private Vba

Private Vba



⚡ ALL INFORMATION CLICK HERE 👈🏻👈🏻👈🏻

































Private Vba
Subscribe to the newletter to receive exclusive content, tips and tricks, tools and downloads. Downloads include 100 Excel VBA Macros ebook for FREE.
When writing VBA macros, the concept of Private or Public is important.  It defines how VBA code within one module can interact with VBA code in another module.
Before we launch into the difference between Public and Private, we first need to understand what Modules are, and how they function.
Modules are the place where we enter and store VBA code.
Worksheet Modules are generally used to trigger code which relate to that specific worksheet.  Each worksheet contains its own module, so if there are 6 worksheets, then you will have 6 Worksheet Modules.
In the screenshot above, the VBA code is contained within the Worksheet Module of Sheet1 and is triggered only when Sheet1 is activated.  Any code in a Worksheet Module based on worksheet events applies only to the worksheet in which the code is stored.
The Workbook Module is generally used to trigger code which relates to workbook level events.
In the screenshot above, the VBA code will run when a workbook is opened.  Every workbook has its own module.
UserForm Modules generally contains code which relates to UserForm events.  Each UserForm contains its own module.
In the screenshot above, the VBA code will run when the user clicks on the button in the UserForm.
Standard Modules are not related to any specific objects and do not have any events related to them.  Therefore, Standard Modules are not triggered by User interaction.  If we are relying on events being triggered, then the Workbook, Worksheet or UserForm Modules may call a macro within a Standard Module.
The screenshot above shows a code which when run, will password protect the ActiveSheet, no matter which workbook or worksheet it is.
The terms Public and Private are used in relation to Modules.  The basic concept is that Public variables, subs or functions can be seen and used by all modules in the workbook while Private variables, subs and functions can only be used by code within the same module.
Let’s look at each of these in turn.
When thinking about the difference between Public and Private subs, the two main areas to consider:
Where Private or Public is excluded, VBA will always treat the sub as if it were Public.
One of the most important features of Private subs is that they do not appear in Excel’s Macro window.
Let’s assume Module1 contains the following two macros:
The Macro window will only display the Public sub.
I don’t want you to jump to the conclusion that all Public Subs will appear in the Macro window.  Any Public sub which requires arguments , will also not appear in this window, but it can still be executed if we know how to reference it.
Can the code be run from another macro
When we think about Private subs, it is best to view them as VBA code which can only be called by other VBA code within the same module.  For example, if Module1 contains a Private Sub, it cannot be called by any code in another module.
Using a simple example here is a Private Sub in Module1:
It will generate an error, as the two macros are in different modules.
But don’t worry, there are many ways to run a macro from another macro . If we use the Application.Run command, it will happily run a Private sub.  Let’s change the code in Module2 to include the Application.Run command:
Instead of an error, the code above will execute the ShowMessage macro.
Working with object based module events
Excel creates the Worksheet, Workbook and UserForm Module events as Private by default, but they don’t need to be.  If they are changed to Public, they can be called from other modules.  Lets look at an example.
Enter the following code into the Workbook Module (notice that I have changed it to a Publc sub).
We can call this from another macro by using the name of the object followed by the name of Public sub.
This means that we can run the Workbook_Open event without needing to actually open the workbook.  If the sub in the Workbook Module is Private, we can still use the Application.Run method noted above.
VBA functions are used to return calculated values.  They have two main uses:
Functions created without the Private or Public declaration are treated as if they are Public.
Calculating values within the worksheet (User Defined Functions)
User Defined Functions are worksheet formulas which operate the same way as other Excel functions, such as SUMIF or VLOOKUP.
The following code snippets are included within Module1:
If we now look at the Insert Function window, the IAmVisible function is available for use:
Functions must be declared in a Standard Module to be used as User Defined Functions in Excel.
Functions used within VBA code operate in the same way as subs; Private functions should only be visible from within the same module.  Once again, we can revert to the Application.Run command to use a Private function from another module.
The code above will happily call the NotVisible private function from Module1.
Generate accurate VBA code in seconds with AutoMacro
AutoMacro is a powerful VBA code generator that comes loaded with an extensive code library and many other time-saving tools and utilities.
Whether you’re an experienced coder looking to save time, or a newbie just trying to get things to work, AutoMacro is the tool for you.
Variables are used to hold values or references to objects which change while the macro runs.  Variables come in 3 varieties, Public, Private and Dim.
Public variables must be declared at the top of the code module, directly after the Option Explicit statement (if you have one) and before any subs or functions.  The following is incorrect and will create an error if we try to use the Public Variable.
The correct approach in Module1 is this (The Public variable is declared before any subs or functions):
As it is a Public variable, we can use and change the variable from any module (of any type) in the workbook.  Look at this example code below, which could run from Module2:
Private Variables can only be accessed and changed by subs and functions within the same Module.  They too must also be declared at the top of the VBA code.
The following demonstrates an acceptable usage of a Private variable.
Most of us learn to create variables by placing the word Dim at the start.  Dim variables behave differently depending on how they are declared.
Dim variables declared within a sub or function can only be used within that sub or function.  In the example below the Dim has been declared in a sub called CreateDim, but used within a sub called UseDim.  If we run the UseDim code, it cannot find the Dim variable and will error.
If a Dim variable is created at the top of the module, before all the subs or functions, it will operate like a Private variable.  The following code will run correctly.
You might be thinking that it sounds easier to create everything as Public, then it can be used anywhere.  A logical, but dangerous conclusion.  It is much better to control all sections of the code.  Ask yourself, if somebody were to use your macro from Excel’s Macro window, should it work?  Or if somebody ran your function as a User Defined Function should it work?  Answers to these questions are a good guiding principle to help decide between Public and Private.
It is always much better to limit the scope of your subs, functions and variables initially, then expand them when required in specific circumstances.
If you’ve found this post useful, or if you have a better approach, then please leave a comment below.
Do you need help adapting this to your needs?
I’m guessing the examples in this post didn’t exactly meet your situation.  We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs.  By taking the time to understand the techniques and principles in this post (and elsewhere on this site) you should be able to adapt it to your needs.
But, if you’re still struggling you should:
What next? Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:
Great job. Very helpful to clear concept specifically related to VBA modules.
Thank you – I appreciate the feedback.
Well structured tutorial on the Modules, Functions, Variables and their scope. Thank you!
It was so helpful! Thank you, it’s the best I could find.
Will a publicly declared variable in a Sheet or the ThisWorkbook module not be accessible in the standard non-sheet-specific modules? For instance, I used “Public myStr as string” in ThisWorkbook’s module, but when referencing that variable in Module 1, Compile tells me it’s an undeclared variable. I have Option Explicit at top of all modules.
Yes, it works if you reference the variables in the right way. In Module1, rather than myStr , you will need to use, ThisWorkbook.myStr .
Hello Thanks for that great explanation. However, I didn’t understand everything and there are error messages in my code. I would like to have an input box appearing when opening the workbook so that the user can insert his username. Afterward, that username he introduced should be used in all module macros that will be called. I tried something, but it didn’t work. Do you have a great solution?
Public UserID As String UserID = InputBox(“Please insert your username”)
Then that UserID should be replaced in all modules. Thanks in advance!!
The declaration of the variable must be at the top of the code window. Like this:
If you’re putting the public variable inside a workbook code module you will need to call the value by referring to the object like this:
Very help and well structured. Thank you!
Clarifies a lot of stuff in Excel VBA that my knowledge of Excel VBA has been pretty hazy over the years in which I have painstackingly taught myself VBA. Thank you very much!
“You might be thinking that it sounds easier to create everything as Public, then it can be used anywhere….It is always much better to limit the scope of your subs, functions and variables initially, then expand them when required in specific circumstances.”
I still don’t understand the _why_ of this. What would be the problem if all subs were public from the start?
The reason is a programing practice known as ‘encapsulation’. We want to group related objects and actions together as if they form a single unit and restrict the potential accidental alteration from other functions. This is most commonly seen in Class Modules. But it is a good practice to adopt.
From a practical view, the biggest issue is that Pubic Subs appear in the Macro box, which can be selected by the user and run and any point. So, if you have a macro which runs several subs, then the user can select any sub and run it individually.
Really good concise and clear article.
Thanks Sumeet – I’m glad you found it useful.
Thank you for this. I am struggling with a very large application I wrote (thousands of lines), but on some PCs it seems like the code is clogging up memory and stalling; weirdly just launching and closing Explorer or any another application gets the macro going again. I did write the code without Option Explicit on so I am in the process of turning it back on a redefining all my variables and then nulling them at the end of each procedure. A big job. Do you think it will help?
It’s impossible to say. It depends what that macro is doing.
It’s good practice to define variables correctly, so it shouldn’t make it any worse.
Is it possible to use a parameter of a function in a sub.
e.g.returns a declaration error on param1 Option Explicit
Public Function demo(param1 As String) As String Call useP1 End Function
Sub useP1() MsgBox (param1) End Sub
My workaround Option Explicit Dim ShowParam1 As String
Public Function demo(param1 As String) As String ShowParam1 = param1 Call useP1 End Function
Sub useP1() MsgBox (ShowParam1) End Sub
You just need to include the arguments as part of the Call statement.
To call this macro use the arguments in the call statement:
Very Useful information. Thank you. Question: is there any way to cancel Public declarations? Thanks
They expire once the macro has stopped executing, but I’m not aware of a way to cancel them completely.
A nice explanation of the concept of Scope in Excel VBA.
Very good article. I’m going through some of these issues as well..
Very well explained, best I’ve seen so far.
Your email address will not be published. Required fields are marked *

Private - Visual Basic | Microsoft Docs
Private vs Public Subs, Variables & Functions in VBA - Excel Off The Grid
excel - vba private scripts - Stack Overflow
Explaining Private vs. Public Declarations — TheSpreadsheetGuru
VBA Private vs Public Procedures (Subs & Functions) - Automate Excel


Sign up with email
Sign up




Sign up with Google



Sign up with GitHub



Sign up with Facebook




Asked
8 years, 8 months ago


Active
5 years, 6 months ago


3,812 11 11 gold badges 32 32 silver badges 51 51 bronze badges


2,507 10 10 gold badges 38 38 silver badges 63 63 bronze badges



You mean only runnable if you are inside that particular VBA project?

–  brettdj
Jun 2 '12 at 10:27



@brettdj, yes, that's what I mean.

–  TPR
Jun 2 '12 at 10:47


52.2k 15 15 gold badges 107 107 silver badges 170 170 bronze badges



but what if want another macro to call it even when it's unauthorized?

–  TPR
Jun 2 '12 at 11:27


135k 15 15 gold badges 188 188 silver badges 234 234 bronze badges



you might want to make the parameter optional, and possibly make it long, or a string, so people can't just try True or False to get the code to run

–  SeanC
Jun 3 '12 at 3:44



Making the parameter Optional will defeat the purpose :) Yes you have a point regarding the making it long or string. I leave the decision with the Asker :)

–  Siddharth Rout
Jun 3 '12 at 3:48

JPMorgan Chase Bank, N.A. Moscow, Russia
The Remote Company No office location
Join our remote team and enjoy work-life balance (JavaScript, NodeJS, React)
Senior React/RN Developer (React, RN, TypeScript, Mobx)

Stack Overflow

Questions
Jobs
Developer Jobs Directory
Salary Calculator
Help
Mobile
Disable Responsiveness


Products

Teams
Talent
Advertising
Enterprise



Company

About
Press
Work Here
Legal
Privacy Policy
Terms of Service
Contact Us



Stack Exchange Network

Technology
Life / Arts
Culture / Recreation
Science
Other


Join Stack Overflow to learn, share knowledge, and build your career.
I know that even private vba scripts can be called by the user, such that making it "private" in fact only hides its name.
However, is there a way to set up a macro so it is only runnable if you are inside that particular VBA project? Not from Excel and not from any VBScript or the likes.
If you want to lock down the code you could
The sample code below checks that the VBA in the host workbook is not protected before running
Honestly, there is no foolproof way around it. You can have certain checks but that's all you can do.
If you are sure that a user will not have access to VBA Code then what brettdj suggested is the best way to go ahead. Protect your project. One cannot run a macro from Excel or from outside Excel if one doesn't know the macro name ;)
The basic intention of making a macro Private is not to prevent it from running but making it invisible to the user. Mostly, the only macros that needs to be private in Excel are the inbuilt Worksheet or Workbook events or macros referred by other macros which necessarily don't need to be accessed by the user. A user can still access them from outside VBA if he or she wants to.
Having said that, you can restrict ( But not STOP - Not referring to disabling your macro security ) the macros from running. Pass an authorization FLAG. Only when it receives an "Authorization", will it run.
Now if you want this macro to be called from VBA then you have to call it like this
This will ensure that the above macro will only run when you allow it to.
Would this method prevent user from running this from VBS?
NO. It won't. However, it won't run till the time the user specifies or gives the "Authorization"

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa . rev 2021.2.2.38474


Mommy Little Boy Pees
Penetration Fucking
Dances Overwatch
Hard Sex Guy
Fire Penetration

Report Page