Option Explicit
Option Compare Text
Public MyDepartment As String
Public MyEmployees As ADODB.Recordset
Dim objBag As New PropertyBag
Private Sub Class_InitProperties()
Set MyEmployees = New ADODB.Recordset
MyEmployees.Fields.Append "EmpName", adVarChar, 30
MyEmployees.Fields.Append "EmpSal", adCurrency
MyEmployees.Open
End Sub
Public Sub SaveMyProperties()
Dim intFile%, bytRec() As Byte
objBag.WriteProperty "MyDepartment", MyDepartment
objBag.WriteProperty "MyEmployees", MyEmployees
Save this a in a file for later retrieval
intFile = FreeFile
If Dir("C:\MyData.txt", vbNormal) = "" Then
Else
Kill "C:\MyData.txt"
End If
Open "C:\MyData.txt" For Binary Access Write As #intFile
bytRec = objBag.Contents
Put #intFile, , bytRec
Close #intFile
End Sub
Public Sub RestoreMyProperties()
Dim intFile%, bytRec() As Byte
Read the saved data from the file.
ReDim bytRec(FileLen("C:\MyData.txt"))
intFile = FreeFile
Open "C:\MyData.txt" For Binary Access Read As #intFile
Get #intFile, , bytRec
objBag.Contents = bytRec
Close #intFile
PropertBag restored. Lets restore the properties now.
MyDepartment = objBag.ReadProperty("MyDepartment")
Set MyEmployees = objBag.ReadProperty("MyEmployees")
End Sub
Private Sub Command1_Click()
Dim objDept As New MyComp.clsMyDept
objDept.MyDepartment = "Research"
Add one employee
objDept.MyEmployees.AddNew
objDept.MyEmployees!EmpName = "Harry"
objDept.MyEmployees!EmpSal = 2500
objDept.MyEmployees.Update
Add second employee
objDept.MyEmployees.AddNew
objDept.MyEmployees!EmpName = "Potter"
objDept.MyEmployees!EmpSal = 3000
objDept.MyEmployees.Update
Save the properties by calling the method from our component
objDept.SaveMyProperties
Set objDept = Nothing
End Sub
Private Sub Command2_Click()
Dim objDept As New MyComp.clsMyDept
Restore properties by calling the method from our component
objDept.RestoreMyProperties
Lets see what is restored
Debug.Print objDept.MyDepartment Will print Research
objDept.MyEmployees.MoveFirst
Debug.Print "" & objDept.MyEmployees!EmpName Will print Harry
objDept.MyEmployees.MoveNext
Debug.Print "" & objDept.MyEmployees!EmpName Will print Potter
Set objDept = Nothing
End Sub
先别激动,你在自己的应用中运行这个酷件之前,必须了解它的局限性。用于保存的时间取决于属性的大小和数据类型。注意大部分时间用在ReadProperty
和 WriteProperty 中。原因很简单,当我们处理象ADO记录集这样的结构型数据时,过程可不象拷贝字节流那样简单。数据也得被解释。