热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

VBA中公共变量的替代方案-AlternativestoPublicVariablesinVBA

Ihaveanumberofpublicvariablesthatarereferencedacrossseveralmodules.Iknowifyoudebug

I have a number of public variables that are referenced across several modules. I know if you debug or hit stop the variable gets cleared out. I have been writing these variables to a spreadsheet so I have them in case they get cleared out, but this is messy. I'd rather have it all stored it code. Is there any alternative to a public variable that never gets cleared?

我有几个模块引用的公共变量。我知道如果你调试或点击停止变量被清除。我一直在把这些变量写到电子表格中,所以如果它们被清除,我会把它们弄清楚,但这很麻烦。我宁愿让它全部存储它代码。是否有任何替代公共变量永远不会被清除?

5 个解决方案

#1


6  

A simple solution would be to store your variables in the registry, and just read/write them as necessary. This has the added benefit of preserving values over multiple Excel sessions (and even after a computer reboot, or a crash - assuming your registry survived it!).

一个简单的解决方案是将变量存储在注册表中,并根据需要读取/写入它们。这具有在多个Excel会话中保留值的额外好处(甚至在计算机重新启动或崩溃之后 - 假设您的注册表幸免于难!)。

EDIT: Also see John Walkenbach's book for more information on this.

编辑:有关此问题的更多信息,请参阅John Walkenbach的书。

EDIT: See below comment by Ioannis for an important consideration.

编辑:请参阅Ioannis的以下评论作为重要考虑因素。


Boilerplate warning: Here be dragons, Twiddle with the Windows registry at your peril, etc etc.

Boilerplate警告:这里有龙,Twiddle与Windows注册表在你的危险等等。


The above warning notwithstanding, realize that almost every program on your Windows computer does something with the registry, and it is not inherently dangerous to do so. Just make sure your code only changes/deletes registry keys which were created by your Excel application.

尽管如此,上述警告意识到Windows计算机上几乎每个程序都对注册表执行某些操作,并且这样做本身并不危险。只需确保您的代码仅更改/删除由Excel应用程序创建的注册表项。


Example procedures using Windows Scripting (I didn't write these; from a quick search):

使用Windows Scripting的示例程序(我没有写这些;来自快速搜索):

Reading from the Registry:

'reads the value for the registry key i_RegKey
'if the key cannot be found, the return value is ""
Function RegKeyRead(i_RegKey As String) As String
Dim myWS As Object

  On Error Resume Next
  'access Windows scripting
  Set myWS = CreateObject("WScript.Shell")
  'read key from registry
  RegKeyRead = myWS.RegRead(i_RegKey)
End Function

Checking if a Registry key exists:

'returns True if the registry key i_RegKey was found
'and False if not
Function RegKeyExists(i_RegKey As String) As Boolean
Dim myWS As Object

  On Error GoTo ErrorHandler
  'access Windows scripting
  Set myWS = CreateObject("WScript.Shell")
  'try to read the registry key
  myWS.RegRead i_RegKey
  'key was found
  RegKeyExists = True
  Exit Function

ErrorHandler:
  'key was not found
  RegKeyExists = False
End Function

Saving a Registry key:

'sets the registry key i_RegKey to the
'value i_Value with type i_Type
'if i_Type is omitted, the value will be saved as string
'if i_RegKey wasn't found, a new registry key will be created
Sub RegKeySave(i_RegKey As String, _
               i_Value As String, _
      Optional i_Type As String = "REG_SZ")
Dim myWS As Object

  'access Windows scripting
  Set myWS = CreateObject("WScript.Shell")
  'write registry key
  myWS.RegWrite i_RegKey, i_Value, i_Type

End Sub

Deleting a key from the Registry:

'deletes i_RegKey from the registry
'returns True if the deletion was successful,
'and False if not (the key couldn't be found)
Function RegKeyDelete(i_RegKey As String) As Boolean
Dim myWS As Object

  On Error GoTo ErrorHandler
  'access Windows scripting
  Set myWS = CreateObject("WScript.Shell")
  'delete registry key
  myWS.RegDelete i_RegKey
  'deletion was successful
  RegKeyDelete = True
  Exit Function

ErrorHandler:
  'deletion wasn't successful
  RegKeyDelete = False
End Function

#2


9  

Here is an example of the CustomDocumentProperties, which I recently started using to store some meta-information (easier than dealing with the CustomXMLParts).

下面是CustomDocumentProperties的一个示例,我最近开始使用它来存储一些元信息(比处理CustomXMLParts更容易)。

The examples below store only string data, but you can also use date, number and Yes/No (which with some finagling you could sub as a Boolean). You are limited to 255 characters for string data.

下面的示例仅存储字符串数据,但您也可以使用日期,数字和是/否(可以使用某些标记作为布尔值)。字符串数据限制为255个字符。

   Sub Test()
   '## Assign a CDP
   SetCustomProperty "myProperty", "some value I want to store"

   End Sub

You can view the CPD's from the Backstage | Info | Properties | Advanced Properties | Custom:

您可以从Backstage中查看CPD信息|属性|高级属性|自定义:

enter image description here

In the event that you End run-time, you can restore the values from the CDP, you can query the property value by:

如果您结束运行时,您可以从CDP恢复值,您可以通过以下方式查询属性值:

myVar = ActiveWorkbook.CustomDocumentProperties("myProperty").Value

myVar = ActiveWorkbook.CustomDocumentProperties(“myProperty”)。值

You can use functions like these to set properties in the CustomDocumentProperties collection:

您可以使用这些函数在CustomDocumentProperties集合中设置属性:

Sub SetCustomProperty(property$, val$)
    Dim cdp As Variant
    Dim hasProperty As Boolean
    If HasCustomProperty(property) Then
        ActiveWorkbook.CustomDocumentProperties(property).Value = val
    Else
        ActiveWorkbook.CustomDocumentProperties.Add property, False, msoPropertyTypeString, val

    End If
End Sub
Private Function HasCustomProperty(property$) As Boolean
Dim cdp As Variant
Dim boo As Boolean
For Each cdp In ActiveWorkbook.CustomDocumentProperties
    If cdp.name = property Then
        boo = True
        Exit For
    End If
Next
HasCustomProperty = boo
End Function

#3


2  

Public variables don´t get erased from memory on debug (break) mode if there are still references that point to them further along in your code. In fact, in some cases if you move your mouse over the variable it will tell you the value at the break.

如果仍有引用在代码中进一步指向它们,则公共变量不会在调试(中断)模式下从内存中删除。事实上,在某些情况下,如果您将鼠标移到变量上,它会告诉您休息时的值。

If you want variables to persist I would use the same method as you are currently using (write them down on an excel worksheet) or a database.

如果你想要保持变量,我将使用你当前使用的相同方法(在excel工作表上写下来)或数据库。

If you do write these variables down, I would recommend you never modify the variable directly, instead use setters and getters that suit your model. For example, if you write them down to a worksheet you might use the following:

如果你确实写下这些变量,我建议你不要直接修改变量,而是使用适合你模型的setter和getter。例如,如果将它们写到工作表,则可以使用以下命令:

public sub setVariable(v as String)
     worksheets("Sheet1").Range("A1").value = v
end sub

public function getVariable() as String
    getVariable = worksheets("Sheet1").range("A1").value
End Function

#4


1  

Here is another solution that might be preferable to my first answer (using the registry) depending on the use case.

这是另一种解决方案,可能比我的第一个答案(使用注册表)更可取决于具体用例。

You could store the values in a "Very Hidden" worksheet. This has the following advantages:

您可以将值存储在“非常隐藏”的工作表中。这具有以下优点:

  1. Prevents the variables from accidentally being destroyed (they are completely invisible to the user)
  2. 防止变量被意外破坏(它们对用户完全不可见)
  3. Allows multiple copies of the workbook to have their own versions of the variables instead of all instances accessing the same values from the registry
  4. 允许工作簿的多个副本具有自己的变量版本,而不是从注册表访问相同值的所有实例
  5. Prevents multiples instances of the workbook from trying to edit the registry keys at the same time
  6. 防止工作簿的多个实例同时尝试编辑注册表项
  7. Allows the workbook to maintain the values after being used on multiple machines, emailed, etc etc
  8. 允许工作簿在多台计算机上使用,通过电子邮件发送等后维护这些值

#5


1  

The TempVars Collection is a great alternative to Public Variables. It won't persist between sessions, but it will persist for the entirety of A session.

TempVars Collection是Public Variables的绝佳替代品。它不会在会话之间持续存在,但它会持续整个A会话。

You will need to add a reference to Microsoft Access 14.0 Object Library though. TempVars are only available from 2007 onward.

您需要添加对Microsoft Access 14.0对象库的引用。 TempVars仅从2007年开始提供。


推荐阅读
  • Java在运行已编译完成的类时,是通过java虚拟机来装载和执行的,java虚拟机通过操作系统命令JAVA_HOMEbinjava–option来启 ... [详细]
  • GetWindowLong函数
    今天在看一个代码里头写了GetWindowLong(hwnd,0),我当时就有点费解,靠,上网搜索函数原型说明,死活找不到第 ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • http:my.oschina.netleejun2005blog136820刚看到群里又有同学在说HTTP协议下的Get请求参数长度是有大小限制的,最大不能超过XX ... [详细]
  • 本文详细介绍了Spring的JdbcTemplate的使用方法,包括执行存储过程、存储函数的call()方法,执行任何SQL语句的execute()方法,单个更新和批量更新的update()和batchUpdate()方法,以及单查和列表查询的query()和queryForXXX()方法。提供了经过测试的API供使用。 ... [详细]
  • 本文介绍了在使用Python中的aiohttp模块模拟服务器时出现的连接失败问题,并提供了相应的解决方法。文章中详细说明了出错的代码以及相关的软件版本和环境信息,同时也提到了相关的警告信息和函数的替代方案。通过阅读本文,读者可以了解到如何解决Python连接服务器失败的问题,并对aiohttp模块有更深入的了解。 ... [详细]
  • FeatureRequestIsyourfeaturerequestrelatedtoaproblem?Please ... [详细]
  • 前景:当UI一个查询条件为多项选择,或录入多个条件的时候,比如查询所有名称里面包含以下动态条件,需要模糊查询里面每一项时比如是这样一个数组条件:newstring[]{兴业银行, ... [详细]
  • 导出功能protectedvoidbtnExport(objectsender,EventArgse){用来打开下载窗口stringfileName中 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • Win10下游戏不能全屏的解决方法及兼容游戏列表
    本文介绍了Win10下游戏不能全屏的解决方法,包括修改注册表默认值和查看兼容游戏列表。同时提供了部分已经支持Win10的热门游戏列表,帮助玩家解决游戏不能全屏的问题。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文讨论了Kotlin中扩展函数的一些惯用用法以及其合理性。作者认为在某些情况下,定义扩展函数没有意义,但官方的编码约定支持这种方式。文章还介绍了在类之外定义扩展函数的具体用法,并讨论了避免使用扩展函数的边缘情况。作者提出了对于扩展函数的合理性的质疑,并给出了自己的反驳。最后,文章强调了在编写Kotlin代码时可以自由地使用扩展函数的重要性。 ... [详细]
author-avatar
菜鸟自学编程
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有