Como declaro uma variável global na VBA?
escrevi o seguinte código:
Function find_results_idle()
Public iRaw As Integer
Public iColumn As Integer
iRaw = 1
iColumn = 1
e recebo a mensagem de erro:
Sabes o que fiz de errado?"atributo inválido no Sub ou função"
tentei usar Global
em vez de Public
, mas tenho o mesmo problema.
8 answers
Tem de declarar as variáveis fora da função:
Public iRaw As Integer
Public iColumn As Integer
Function find_results_idle()
iRaw = 1
iColumn = 1
Se só quiser que as variáveis durem a vida útil da função, use Dim
(abreviatura de dimensão) dentro da função ou sub para declarar as variáveis:
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
Aglobal variável (como os SLaks assinalaram) é declarada fora da função usando a palavra-chave Public
. Esta variável estará disponível durante a vida útil da sua aplicação em execução. No caso do Excel, isto significa as variáveis estarão disponíveis enquanto esse Manual específico do Excel estiver aberto.
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.
Você também pode ter variáveis que só estão acessíveis dentro de um determinado módulo (ou classe), declarando-as com a palavra-chave Private
.
Se você está construindo uma grande aplicação e sente a necessidade de usar variáveis globais, eu recomendaria a criação de um módulo separado apenas para suas variáveis globais. Isto deve ajudá-lo a localizá-los num só lugar.
Para usar variáveis globais, inserir um novo módulo a partir da interface de projecto VBA e declarar variáveis usando 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).
Você pode verificar esta referência MSDN para mais informações sobre a declaração de variáveis e esta outra questão de estouro de pilha para mais informações sobre como as variáveis saem do âmbito.
Mais duas coisas rápidas:- organize-se ao usar variáveis de nível do livro de trabalho, para que o seu código não fique confuso. Prefer Functions (with proper data tipos) ou argumentos de passagem ByRef .
- Se quiser uma variável para preservar o seu valor entre as chamadas, pode usar a declaração estática.
Se esta função está em um módulo / classe, você poderia simplesmente escrevê-los fora da função, então ela tem Global Scope
. Âmbito Global significa que a variável pode ser acedida por outra função no mesmo módulo / classe (se usar dim
como declaração, use public
Se quiser que as variáveis possam ser acedidas por todas as funções em todos os módulos):
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
Criar um inteiro público na declaração geral.
Então na sua função você pode aumentar o seu valor de cada vez. Veja exemplo (função para salvar anexações de um e-mail como 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
Também pode usar -
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
o seu teste no escritório 2010
Uma boa maneira de criar variáveis públicas / globais é tratar a forma como um objeto de classe e declarar propriedades e usar Propriedade pública obter [variável] para acessar propriedade/método. Também pode ser necessário referenciar ou passar uma referência ao módulo de forma instanciada. Você vai obter erros se você chamar métodos para formulários/relatórios que estão fechados.
Exemplo: passe-me.Formulario.Modulo.Pai para sub / função não dentro da forma.
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
Então no outro módulo você poderia acessar:
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
Se usar a ligação tardia como eu verifico sempre se há valores nulos e objectos que não são nada antes de tentar fazer qualquer processamento.