VBA use global variable in userform code

徘徊边缘 提交于 2020-01-16 20:04:54

问题


I'm working in Excel 2010 VBA. Is there a way of accessing values in global variables declared outside a userform, in code inside the userform? Code inside my userform returns the global variable as null - can't work out why!

The variable is declared in the ThisWorkbook module as:

Public TargetCell As Range
Public TargetCellWorksheet as Worksheet
Public CurrentValue As Long

Inside the userform, I have this code on the "Update" button:

Private Sub Update_Click()
    MsgBox ("Start of Update sub. TargetCellWorksheet =" & TargetCellWorksheet)
End Sub

The msgbox returns "" for the variable.

Hoping someone may be able to help me understand this and how to access the variable inside the userform? Thank you in advance


回答1:


As for the problem itself, you declare

Public TargetCellWorksheet as Worksheet

and then try to show it into a MsgBox:

MsgBox ("Start of Update sub. TargetCellWorksheet =" & TargetCellWorksheet)

Did you maybe mean TargetCellWorksheet.Name, or TargetCellWorksheet.Range("A1").Value, since the MsgBox expects to receive a string?

However, if you're sure about your code, it might depend on the fact that the variable is not properly declared as Public and it goes at module level only. You might want to add a property to your form, if the variable is part of the form itself (I assume that you meant to use CurrentValue, but you can simply change the type of the property from Long to Worksheet and use it instead):

This goes inside the code of your form

Dim pCurrentValue As Long
Public Property Get CurrentValue() As Long
    CurrentValue = pCurrentValue 
End Property
Public Property Let CurrentValue (value As Long)
    pCurrentValue = value
End Property

Hence, passing the variable from the module to the form like this:

This goes into your module, before you enter the code of the form

Dim myForm As New yourForm
myForm.CurrentValue  = whateverYourVariableIs

and so using the variable inside your form like this:

You can hence use your variable by calling it from the property of the form

myVariableInTheForm = Me.CurrentValue 

I must say that, however, it is strange that a public variable is not reaching the stack of the form. Are you sure you're not only declaring the variable without assigning any value before?



来源:https://stackoverflow.com/questions/28044194/vba-use-global-variable-in-userform-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!