我正在试图弄清楚如何从Access表单中获取表单,控件和属性数据,该表单不在我启动代码的Access数据库中。我已经弄清楚如何从数据库中获取数据,但我无法弄清楚如何从数据库外部的表单中获取数据。
我认为如果我要将外部数据库设置为当前数据库,我的代码就可以了。但是,在执行“For Each frm In appAccess.Forms”后,光标将转到“End Sub”。
我尝试使用容器,我能够返回表单名称,但我无法弄清楚如何遍历控件和属性集合。
以下是与我的第一个想法相关的代码。我的最终目标是能够将表单数据保存在不同的数据库中。我的代码是否存在小错误,或者我应该使用不同的方法来获取数据?
Sub GetControlForm()
Dim strPath As String
Dim frm As Form
Dim ctrl As Control
Dim prop As Property
Dim appAccess As New Access.Application
Dim dbs As DAO.Database
strPath = "C:\Users\Tyrone\Desktop\Test14.accdb"
Set appAccess = CreateObject("Access.Application")
appAccess.OpenCurrentDatabase (strPath)
'MsgBox appAccess.CurrentDb.Name
For Each frm In appAccess.Forms
MsgBox frm.Name
For Each ctrl In frm.Controls
MsgBox ctrl.Name
MsgBox ctrl.ControlType.TypeName
MsgBox TypeName(ctrl)
For Each prop In ctrl.Properties
If prop.Name = "RowSource" Then
MsgBox "stop it"
End If
If (TypeName(ctrl) = "ComboBox" Or TypeName(ctrl) = "TextBox") And (prop.Name = "RowSource" Or prop.Name = "ControlSource") Then
MsgBox prop.Value
End If
Next prop
Next ctrl
Next frm
End Sub
答案 0 :(得分:3)
您的For Each
无法循环的原因是远程数据库中的表单未打开。根据{{3}}:
" Visual Basic中 Forms 集合的属性引用表单 目前正在开放。"
试试这个:
Sub GetControlForm()
Dim strPath As String
Dim obj As AccessObject
Dim frm As Form
Dim ctrl As Control
Dim prop As Property
Dim appAccess As New Access.Application
Dim dbs As DAO.Database
strPath = "C:\Users\Tyrone\Desktop\Test14.accdb"
Set appAccess = CreateObject("Access.Application")
appAccess.OpenCurrentDatabase (strPath)
'MsgBox appAccess.CurrentDb.Name
For Each obj In appAccess.CurrentProject.AllForms
appAccess.DoCmd.OpenForm obj.Name
Set frm = appAccess.Forms(obj.Name)
MsgBox frm.Name
For Each ctrl In frm.Controls
MsgBox ctrl.Name
'MsgBox ctrl.ControlType.TypeName
MsgBox TypeName(ctrl)
For Each prop In ctrl.Properties
If prop.Name = "RowSource" Then
MsgBox "stop it"
End If
If (TypeName(ctrl) = "ComboBox" Or TypeName(ctrl) = "TextBox") And (prop.Name = "RowSource" Or prop.Name = "ControlSource") Then
MsgBox prop.Value
End If
Next prop
Next ctrl
appAccess.DoCmd.Close acForm, frm.Name
Next obj
Set frm = Nothing
appAccess.CloseCurrentDatabase
Set appAccess = Nothing
End Sub