如何为全局变量赋值以供全局使用

问题描述 投票:1回答:2

我有一个字符串Application.hWndAccessApp出现在多行代码中调用自定义MsgBoxT。不是在模块和类的每个实例上编写Application.hWndAccessApp,而是希望将它分配给公共变量,例如hid as string。我知道声明一个公共变量然后在函数或SubRoutine中赋值。

在这里,我希望全局分配该值,以便每次我想使用MsgBoxT函数时它都可用于所有模块/类。

编辑:我按照下面的评论提示,但它给了Error # 13: Type Mismatch

Global Const hid = "Application.hWndAccessApp"

然后我用下面的函数调用它:

MsgBoxT hid, "Record Updated!", "Confirmation", VbInformation, 0 , 1000

我的MsgBox函数是公开声明的:

Public Declare PtrSafe Function MsgBoxT _
Lib "user32" _
Alias "MessageBoxTimeoutA" ( _
   ByVal hwnd As LongPtr, _
   ByVal lpText As String, _
   ByVal lpCaption As String, _
   ByVal wType As VbMsgBoxStyle, _
   ByVal wLange As Long, _
   ByVal dwTimeout As Long) _
As Long
vba access-vba
2个回答
2
投票

根据更新的问题,变量是LongPtr。由于它在Runtime上初始化,你有一个选择:

  1. 声明您将在第二时刻分配的Global LongPtr: Global hid As LongPtr hid = Application.hWnd

使用下面问题的更新代码,它现在运行顺利:

Global hid As LongPtr

Public Declare PtrSafe Function MsgBoxT _
Lib "user32" _
Alias "MessageBoxTimeoutA" ( _
   ByVal hwnd As LongPtr, _
   ByVal lpText As String, _
   ByVal lpCaption As String, _
   ByVal wType As VbMsgBoxStyle, _
   ByVal wLange As Long, _
   ByVal dwTimeout As Long) _
As Long

通过这些更改,它可以工作(在我的PC上测试):

'On This_Workbook
Private Sub Workbook_Open()
    hid = Application.hwnd
End Sub

'Anywhere in the code
Sub test()
    MsgBoxT hid, "Record Updated!", "Confirmation", vbInformation, 0, 1000
End Sub

enter image description here


0
投票
Public hid as string

Sub Main()
    hid = Application.hWndAccessApp
End Sub

要么

Private Sub Workbook_Open()

   hid = Application.hWndAccessApp

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.