programing

VBA에서 글로벌 변수를 선언하려면 어떻게 해야 하나요?

instargram 2023. 4. 12. 21:45
반응형

VBA에서 글로벌 변수를 선언하려면 어떻게 해야 하나요?

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

Function find_results_idle()

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

에러 메세지가 표시됩니다.

"하위 또는 함수의 잘못된 특성"

내가 뭘 잘못했는지 알아?

사용하려고 했습니다.GlobalPublic

나는 함수 자체를 Public이라고 선언하려고 했지만 그것도 소용이 없었다.

글로벌 변수를 작성하려면 어떻게 해야 합니까?

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

Public iRaw As Integer
Public iColumn As Integer

Function find_results_idle()
    iRaw = 1
    iColumn = 1

이것은 범위에 관한 질문입니다.

가 함수의 , 「」를 합니다.Dim(Dimension의 약자) 함수 또는 서브 내에서 변수를 선언합니다.

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 문을 사용할 수 있습니다.

쓸 수 있기 에, 이 함수는 모듈/클래스에 있는 쓸 수 .Global Scope. Global Scope는 동일한 모듈/클래스의 다른 함수에 의해 변수에 액세스할 수 있음을 의미합니다(사용하는 경우).dim선언문으로, 사용public모든 모듈의 모든 기능을 통해 변수에 액세스할 수 있습니다).

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

또, 다음과 같은 것도 사용할 수 있습니다.

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

Office 2010에서 테스트 완료

워크북에 속성을 할당하는 것이 가장 좋은 방법입니다.

워크북이 열려 있는 한 범위는 유효합니다.

Public WhenOpened As Date

Private Sub Workbook_Open()
   ThisWorkbook.WhenOpened = Now()
End Sub

General Declaration(General Declaration).

그런 다음 함수에서 매번 값을 늘릴 수 있습니다.예(이메일의 첨부 파일을 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

Public/Global 변수를 만드는 좋은 방법은 폼을 클래스 오브젝트처럼 처리하여 속성을 선언하고 Public Property Get [variable]를 사용하여 속성/메서드에 액세스하는 것입니다.또한 인스턴스화된 양식 모듈을 참조하거나 참조를 전달해야 할 수도 있습니다.닫힌 폼/리포트에 메서드를 호출하면 오류가 발생합니다.
예: Me.Form을 전달합니다.Module. 내부 형식이 아닌 하위/기능으로 부모.

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

다른 모듈에서는 다음 기능에 액세스할 수 있습니다.

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

나처럼 Late Binding을 사용하는 경우 처리를 시도하기 전에 항상 Null 값 및 아무것도 아닌 개체를 확인합니다.

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

반응형