VBA:保存Excel表单状态

时间:2014-12-01 21:04:29

标签: excel forms vba state

我注意到一些Excel加载项会将状态从一次使用维护到另一次使用。一个例子是Solver加载项,即使在关闭并重新打开Excel电子表格后也会保留表单数据。

表单元素保存在哪里,表单可以保持状态?我有兴趣在自定义加载项中模拟此行为,但无法弄清楚如何使其工作。

3 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

答案 2 :(得分:1)

我最终需要保存超过255个字符,因此隐藏的名称对我不起作用。所以我最终使用了没有255个字符限制的工作表自定义属性。我保存表单状态然后恢复状态的函数最终看起来像这样:

保存状态:

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