使用MS Access和VBA更新Ms Word文档中的(字段代码:数据库)字段

时间:2017-04-06 21:21:29

标签: vba ms-access ms-word access-vba word-vba

Ms Word Database字段在Word表格中插入数据库查询的结果。

我想使用VBA在ms字中填充表,我已经使用了VBA MsAccess& MsWord书签,来自数据的模板使文档很难维护。我发现MSword有选项insert database,允许你在msaccess中实现数据并在更新期间保留预格式化。 以下数据库字段代码来自我的Access数据库通过ODBC使用Database命令进行的查询:

  

{DATABASE \ d“C:\ My Data Sources \ To Test World.odc”\ c   “Provider = MSDASQL.1; Persist Security Info = True; Extended   属性= \“DSN = MS Access数据库; DBQ = H:\ CIP   BOOK \ CIP2.accdb; DefaultDir = H:\ CIP BOOK; DriverId = 25; FIL = MS   Access; MaxBufferSize = 2048; PageTimeout = 5; \“;初始目录= H:\ CIP   BOOK \ CIP2.accdb“\ s”SELECT SELECT DescriptionTAEntry Title,   Memo FROM qryTransactions ExtendedWordFill_test在哪里   (( Project_id ='PCP13ZOOA06 '))“\ l”26“\ b”191“\ h * MERGEFORMAT   }

首先我的wdFieldDatabase有Fields(Index),其中Index是索引号(Field对象)。索引号表示字段在选择,范围或文档中的位置

其次我找到了Fields.Add方法(Word) 此示例是否添加字段ListNum

 Selection.Collapse Direction:=wdCollapseEnd 
ActiveDocument.Fields.Add Range:=Selection.Range, _ 
 Type:=**wdFieldListNum**, Text:="\s 3"

我想要的是使用VBA更新基于索引位置的(字段代码:数据库字段)中的代码并更改( Project_id ='PCP13ZOOA06 )。其他替代方法是使用在VBA中创建代码,在特定范围,文档位置添加字段数据库。我想从访问中管理这个,想法是创建超过2oo项目的费用表的状态报告。

Field codes: Database field

1 个答案:

答案 0 :(得分:1)

我现在无法对它进行测试,但是不会为你做这样的工作吗?

Option Explicit

Public Sub UpdateDatabaseField()
    Dim fldTarget As Field: Set fldTarget = ActiveDocument.Fields(1) ' TODO: Find your field based on your knowledge of your document
    Dim strProjectIdNew As String: strProjectIdNew = "123456" ' TODO: Determine new project code

    Dim strCodeOld As String: strCodeOld = fldTarget.Code.Text
    Dim ixBegin As Long: ixBegin = InStr(1, strCodeOld, "Project_id") + Len("Project_id")
    Dim ixEnd As Long: ixEnd = InStr(ixBegin, strCodeOld, ")")
    Dim strCodeNew As String: strCodeNew = Left(strCodeOld, ixBegin) & "='" & strProjectIdNew & "'" & Mid(strCodeOld, ixEnd)
    fldTarget.Code.Text = strCodeNew
End Sub

最终代码:

Public Sub UpdateDatabaseField()
Dim fldTarget As Field: Set fldTarget = ActiveDocument.Fields(1) ' TODO: Find your field based on your knowledge of your document
Dim strProjectIdNew As String: strProjectIdNew = "PCP13ZOOA08" ' TODO: Determine new project code

Dim strCodeOld As String: strCodeOld = fldTarget.Code.Text
Dim ixBegin As Long: ixBegin = InStr(1, strCodeOld, "Project_id") + Len("Project_id") - 0
Dim ixEnd As Long: ixEnd = InStr(ixBegin, strCodeOld, ")")
Dim strCodeNew As String: strCodeNew = Left(strCodeOld, ixBegin) & "='" & strProjectIdNew & "'" & Mid(strCodeOld, ixEnd)
fldTarget.Code.Text = strCodeNew
ActiveDocument.Fields(1).Update

End Sub