如何调用全局字符串变量

时间:2018-04-02 14:15:12

标签: excel excel-vba vba

我有以下全局变量:

Option Explicit

Public locationCode As String                               'Access the locationCode on the form anywhere on the project

Public Sub Settings()

'Declaration to access the data entered in the
'locationCode from anywhere on the project

locationCode = frmEnterLocation.txtLocationCode.Value


End Sub

但是当我尝试在项目的另一部分使用我的变量时,例如:

Private Sub cmdOKButton_Click()


frmEnterLocation.txtLocationCode.SetFocus


If locationCode = "" Then

    MsgBox "You have not entered a Location Code", vbCritical, "Please Enter a Location Code"


           frmEnterLocation.txtLocationCode.SetFocus

Else

     Unload Me

End Sub

变量未存储文本框中的值。如何在我的Sub上正确调用此属性?

2 个答案:

答案 0 :(得分:1)

通过文本框分配值,在表单代码模块中更改事件

您必须在用户表单中的文本框txtLocationCode中的每次更改后分配文本框值,以便将其存储:

Private Sub txtLocationCode_Change()
' assign new value to global variable after each change in text box txtLocationCode
  locationCode = Me.txtLocationCode.Value
End Sub

从标准代码模块调用Userform

要进行设置,您只需在全局声明locationCode后显示userform的实例,并在用户堕胎后通过红色[x]恢复旧值的变量(请参阅下面的{{1} }})。

Sub UserForm_QueryClose

注意: Option Explicit ' declaration head of a standard code module ' Access the locationCode on the form anywhere on the project Public locationCode As String Public locationCodeOld As String Sub Settings() With New frmEnterLocation .Show vbModeless End With End Sub 语句允许您正确卸载(销毁)被调用的userform实例。

完整的Userform代码模块(不含With New .. - >见下文)

UserForm_QueryClose

建议添加到用户表单代码模块

这允许您通过红色[x]:

恢复用户堕胎后的旧值
Option Explicit

Private Sub txtLocationCode_Change()  ' << as discussed above
' assign new value to global variable after each change in text box txtLocationCode
  locationCode = Me.txtLocationCode.Value
End Sub

Private Sub cmdOKButton_Click()
' SetFocus isn't executed after MsgBox, so use a Label1 info
If locationCode = "" Then
   Me.Caption = "No Location Code entry yet"
   Me.Label1.Caption = "Please Enter a Location Code"
   Me.txtLocationCode.SetFocus
Else
   Me.Caption = "Location code is " & locationCode
   Me.Label1.Caption = "Location Code"
   Me.Hide
End If
End Sub

Private Sub UserForm_Activate()
' remember old setting of locationCode
  locationCodeOld = locationCode
' display current setting in text box and headers
  Me.txtLocationCode.Value = locationCode
  Me.txtLocationCode.SetFocus
  Me.Caption = "Location code is " & IIf(Len(locationCode) = 0, " not yet entered", locationCode)
  Me.Label1.Caption = IIf(Len(locationCode) = 0, "Please enter ", "") & "Location Code"
End Sub

答案 1 :(得分:0)

Public locationCode As String放在标准公共模块代码表的声明区域(即顶部),而不是私有工作表代码表。