Programming

VBA에서 전역 변수를 어떻게 선언합니까?

procodes 2020. 7. 5. 21:37
반응형

VBA에서 전역 변수를 어떻게 선언합니까?


다음 코드를 작성했습니다.

Function find_results_idle()

    Public iRaw As Integer
    Public iColumn As Integer
    iRaw = 1
    iColumn = 1

그리고 오류 메시지가 나타납니다.

"하위 또는 함수의 유효하지 않은 속성"

내가 뭘 잘못했는지 알아?

Global대신 사용하려고했지만 Public같은 문제가 발생했습니다.

나는 함수 자체를`Public '으로 선언하려고 시도했지만 그다지 좋지 않았다.

전역 변수를 만들려면 어떻게해야합니까?


함수 외부에서 변수를 선언해야합니다.

Public iRaw As Integer
Public iColumn As Integer

Function find_results_idle()
    iRaw = 1
    iColumn = 1

이것은 scope에 대한 질문 입니다.

변수가 함수의 수명 동안 만 지속되도록 하려면 함수 또는 sub 내부에서 ( Dimension의Dim 줄임말)을 사용 하여 변수를 선언하십시오.

Function AddSomeNumbers() As Integer
    Dim intA As Integer
    Dim intB As Integer
    intA = 2
    intB = 3
    AddSomeNumbers = intA + intB
End Function
'intA and intB are no longer available since the function ended

글로벌 변수 (SLaks 지적대로) 사용하여 함수의 외부에서 선언 Public키워드를. 이 변수는 실행중인 응용 프로그램 수명 동안 사용할 수 있습니다. Excel의 경우 특정 Excel 통합 문서가 열려있는 한 변수를 사용할 수 있습니다.

Public intA As Integer
Private intB As Integer

Function AddSomeNumbers() As Integer
    intA = 2
    intB = 3
    AddSomeNumbers = intA + intB
End Function
'intA and intB are still both available.  However, because intA is public,  '
'it can also be referenced from code in other modules. Because intB is private,'
'it will be hidden from other modules.

Private키워드 로 선언하여 특정 모듈 (또는 클래스) 내에서만 액세스 할 수있는 변수를 가질 수도 있습니다 .

큰 응용 프로그램을 작성하고 전역 변수를 사용해야 할 필요가 있다면 전역 변수에 대해 별도의 모듈을 만드는 것이 좋습니다. 이를 통해 한 곳에서 추적 할 수 있습니다.


전역 변수를 사용하려면 VBA 프로젝트 UI에서 새 모듈을 삽입하고 다음을 사용하여 변수를 선언하십시오. Global

Global iRaw As Integer
Global iColumn As Integer

문제는 다른 사람이 말한 것처럼 실제로 범위에 관한 것입니다.

간단히 말해이 "모듈"을 고려하십시오.

Public Var1 As variant     'Var1 can be used in all
                           'modules, class modules and userforms of 
                           'thisworkbook and will preserve any values
                           'assigned to it until either the workbook
                           'is closed or the project is reset.

Dim Var2 As Variant        'Var2 and Var3 can be used anywhere on the
Private Var3 As Variant    ''current module and will preserve any values
                           ''they're assigned until either the workbook
                           ''is closed or the project is reset.

Sub MySub()                'Var4 can only be used within the procedure MySub
    Dim Var4 as Variant    ''and will only store values until the procedure 
End Sub                    ''ends.

Sub MyOtherSub()           'You can even declare another Var4 within a
    Dim Var4 as Variant    ''different procedure without generating an
End Sub                    ''error (only possible confusion). 

변수 선언에 대한 자세한 내용은 MSDN 참조 를 참조하고 변수 가 범위를 벗어나는 방법에 대한 자세한 내용은 다른 스택 오버플로 질문 을 참조하십시오.

다른 두 가지 빠른 것 :

  1. 통합 문서 수준 변수를 사용할 때 체계화되므로 코드가 혼동되지 않습니다. 함수 (적절한 데이터 유형) 또는 ByRef 인수 전달을 선호하십시오 .
  2. 호출간에 변수 값을 유지하려면 Static 문을 사용할 수 있습니다 .

If this function is in a module/class, you could just write them outside of the function, so it has Global Scope. Global Scope means the variable can be accessed by another function in the same module/class (if you use dim as declaration statement, use public if you want the variables can be accessed by all function in all modules) :

Dim iRaw As Integer
Dim iColumn As Integer

Function find_results_idle()
    iRaw = 1
    iColumn = 1
End Function

Function this_can_access_global()
    iRaw = 2
    iColumn = 2
End Function

Create a public integer in the General Declaration.

Then in your function you can increase its value each time. See example (function to save attachements of an email as CSV).

Public Numerator As Integer

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim FileName As String

saveFolder = "c:\temp\"

     For Each objAtt In itm.Attachments
            FileName = objAtt.DisplayName & "_" & Numerator & "_" & Format(Now, "yyyy-mm-dd H-mm-ss") & ".CSV"
                      objAtt.SaveAsFile saveFolder & "\" & FileName
                      Numerator = Numerator + 1

          Set objAtt = Nothing
     Next
End Sub

A good way to create Public/Global variables is to treat the Form like a class object and declare properties and use Public Property Get [variable] to access property/method. Also you might need to reference or pass a Reference to the instantiated Form module. You will get errors if you call methods to forms/reports that are closed.
Example: pass Me.Form.Module.Parent into sub/function not inside form.

Option Compare Database 
Option Explicit
''***********************************''
' Name: Date: Created Date Author: Name 
' Current Version: 1.0
' Called by: 
''***********************************''
' Notes: Explain Who what when why... 
' This code Example requires properties to be filled in 
''***********************************''
' Global Variables
Public GlobalData As Variant
''***********************************''
' Private Variables
Private ObjectReference As Object
Private ExampleVariable As Variant
Private ExampleData As Variant
''***********************************''
' Public properties
Public Property Get ObjectVariable() As Object
   Set ObjectVariable = ObjectReference
End Property 
Public Property Get Variable1() As Variant 
  'Recommend using variants to avoid data errors
  Variable1 = ExampleVariable
End property
''***********************************''
' Public Functions that return values
Public Function DataReturn (Input As Variant) As Variant
   DataReturn = ExampleData + Input
End Function 
''***********************************''
' Public Sub Routines
Public Sub GlobalMethod() 
   'call local Functions/Subs outside of form
   Me.Form.Refresh
End Sub
''***********************************''
' Private Functions/Subs used not visible outside 
''***********************************''
End Code

So in the other module you would be able to access:

Public Sub Method1(objForm as Object)
   'read/write data value
   objForm.GlobalData
   'Get object reference (need to add Public Property Set to change reference object)
   objForm.ObjectVariable
   'read only (needs Public property Let to change value)
   objForm.Variable1
   'Gets result of function with input
   objForm.DataReturn([Input])
   'runs sub/function from outside of normal scope
   objForm.GlobalMethod
End Sub

If you use Late Binding like I do always check for Null values and objects that are Nothing before attempting to do any processing.


Also you can use -

Private Const SrlNumber As Integer = 910

Private Sub Workbook_Open()
    If SrlNumber > 900 Then
        MsgBox "This serial number is valid"
    Else
        MsgBox "This serial number is not valid"
    End If
End Sub

Its tested on office 2010

참고URL : https://stackoverflow.com/questions/2722146/how-do-i-declare-a-global-variable-in-vba

반응형