VBA:保存Excel表单状态

我注意到一些Excel加载项从一个用户维护状态到另一个用户。 Solver加载项就是一个例子,即使在closures和重新打开Excel电子表格之后,该加载项也将维护表单数据。

表单元素被保存在哪里以便表单可以保持状态? 我感兴趣的是在一个自定义加载项中模拟这种行为,并没有能够弄清楚如何使其工作。

设置存储在工作表上的隐藏名称中:

Sub Test() Dim nName As Name For Each nName In ActiveWorkbook.Names Debug.Print nName.Name, nName.RefersTo Next nName End Sub 

使用文档的caching属性: http : //msdn.microsoft.com/en-us/library/microsoft.visualstudio.tools.applications.runtime.cachedattribute.aspx

我最终需要保存超过255个字符,所以隐藏的名字不适合我。 所以我最终使用了不具有255字符限制的工作表自定义属性。 我的function来保存一个窗体的状态,然后恢复状态结束了看起来像这样:

保存状态:

 Private Sub save_form_state() Dim prop As CustomProperty For Each Control In Me.Controls '' only saving state for text boxes and ref edits If TypeName(Control) = "TextBox" Or TypeName(Control) = "RefEdit" Then '' only save state for controls with values -- custom properties can't have null values If Control.Value <> "" Then For Each prop In ActiveWorkbook.ActiveSheet.CustomProperties '' if the name already exists in custom properties then delete it If prop.Name = Control.Name Then prop.Delete Next prop '' any dupe has been deleted, so write the key and value ActiveWorkbook.ActiveSheet.CustomProperties.Add Name:=Control.Name, Value:=Control.Value End If End If Next Control End Sub 

恢复状态:

 Private Sub restore_form_state() Dim prop As CustomProperty '' go through every text box and ref edit control then see if there's a custom property '' with matching name. If so, set the value of the control = custom property value For Each Control In Me.Controls If TypeName(Control) = "TextBox" Or TypeName(Control) = "RefEdit" Then For Each prop In ActiveWorkbook.ActiveSheet.CustomProperties If Control.Name = prop.Name Then Control.Value = prop.Value End If Next prop End If Next Control End Sub