Excel VBA:存储另一个工作簿可读的版本代码

我们有一个工作簿模板通过电子邮件发送,填写和返回。 返回时,我们为工作簿分配一个唯一的编号。 目前唯一编号附加到工作簿名称。

当工作簿没有正确填写时,这是一个问题,我们必须将其发送出去进行更正,并将名称更改后再接收。

工作簿由VBA处理,数据库根据唯一编号进行更新。 如果工作簿号码再次进入,则假定为更新,logging被replace。

我们的想法是将唯一编号存储在隐藏的工作表中。 有没有另外一种不需要隐藏工作表的方法 – 比如通过代码读取和写入工作簿中的一些隐藏字段或全局常量的能力?

您可以使用CustomDocumentProperties集合来存储所需的值,如下所示:

Dim p As DocumentProperty ' Delete any existing property with this name For Each p In ThisWorkbook.CustomDocumentProperties If (p.Name = "uniqueNumber") Then p.Delete Exit For End If Next p ' Create the property with the required value ThisWorkbook.CustomDocumentProperties.Add "uniqueNumber", False, msoPropertyTypeString, "42846479" MsgBox ThisWorkbook.CustomDocumentProperties("uniqueNumber") 

您可以使用WorkBook的名称集合:

 Sub StoreName(key As String, val As Variant) Dim WB As Workbook Set WB = ThisWorkbook WB.Names.Add key, "=" & val 'to force val to be interpreted as a named formula End Sub Function ReadName(key As String) As Variant Dim WB As Workbook Set WB = ThisWorkbook ReadName = Mid(WB.Names(key), 2) End Function 

testing像:

 Sub test() StoreName "bob", "1234" Debug.Print ReadName("bob") End Sub 

打印1234

还有其他方法来存储持久性数据。 例如,这里是一个有趣的博客文章 。