2

We have a workbook template emailed out, filled and returned by email. When returned, we assign a unique number to the workbook. Currently the unique number is appended to the workbook name.

This is a problem when the workbook isn't filled in correctly and we have to send it out for correction and receive it back with the name changed.

The workbook is processed by VBA and a database is updated based on the unique number. If a workbook with the same number comes in again, it is assumed to be an update and records are replaced.

Our idea is to store the unique number in a hidden worksheet. Is there another way that doesn't require a hidden worksheet - such as the ability to read and write some hidden fields or global constants in a workbook through code?

1
  • Variables don't exist until code is compiled & run so I'd say no, but maybe someone here will come up with something. Commented Mar 16, 2017 at 23:20

2 Answers 2

2

You can use a WorkBook's Name collection:

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

Tested like:

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

Which prints 1234.

There are still other ways to store persistent data. For example, here is an interesting blog post.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use the CustomDocumentProperties collection to store the value you need, like this:

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")

2 Comments

Actually, you could use one of the built-in properties, like Category or Comment or Status. Read/Write ThisWorkbook.BuiltinDocumentProperties("Comments")
This worked successfully for both writing and reading from a different workbook. Regarding BuiltinDocumentProperties, this is also a good solution however there seems to be a greater chance of being overwritten inadvertently as they are common to workbooks and accessible in the information tab.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.