JenniferMurphy
Well-known Member
- Joined
- Jul 23, 2011
- Messages
- 2,691
- Office Version
- 365
- Platform
- Windows
I am working on a very complex (for me, at least) macro that will process a large sheet table. The table has several "helper" rows above the table that tell the macro what to do with the data in each column of the table. The code works, but it is difficult to read. I want to move sections of the code to subroutines. The subroutines will be easier to read and understand and the top level code will be much simpler and the logic flow clearer.
Here's the problem. There are quite a few variables and some of them are fairly large. And some of the subroutines will need to make changes to some of the values in some of the arrays. As I see it, I have 3 options:
#2 seems like the preferred way to go. The subroutine can work with the actual arrays, so any changes will be available to the calling code. And the calling syntax clearly spells out which variables each subroutine will use.
#3 seems like the simplest. I only need a few global variables. The rest can be passed. As I understand it, there are 3 types of scope of VBA variables:
Here's a little test code:
My plan is to make a few of these variables module-level (Private). Any comments?
Here's the problem. There are quite a few variables and some of them are fairly large. And some of the subroutines will need to make changes to some of the values in some of the arrays. As I see it, I have 3 options:
- Pass the variables as ByVal parameters.
- Pass the variables as ByRef parameters.
- Make some of the variables global so they don't have to be passed.
#2 seems like the preferred way to go. The subroutine can work with the actual arrays, so any changes will be available to the calling code. And the calling syntax clearly spells out which variables each subroutine will use.
#3 seems like the simplest. I only need a few global variables. The rest can be passed. As I understand it, there are 3 types of scope of VBA variables:
- Procedure level. Declare these with a DIm statement inside the procedure. They arfe only available to that procedure.
- Module level. Declare these with a Private statement outside all procedures in that module, usually at the top. They are available to all procedures in that module.
- Global level. Declare these with a Public statement outside all procedures in any module, usually at the top. They are available to all procedures in all modules.
Here's a little test code:
Code:
Private test As String
Sub temp1()
test = "temp1"
Debug.Print test & " in test1"
Call temp2
Debug.Print test & " in test1"
End Sub
Sub temp2()
test = "temp2"
Debug.Print test & " in test2"
End Sub
My plan is to make a few of these variables module-level (Private). Any comments?