是否可以让Microsoft Word 2010自动更新在文件打开时使用Microsoft Query插入到文档中的SQL数据?
在Word中使用插入数据库功能时,在配置数据源并创建SQL查询后,数据将作为表插入到当前打开的文档中。在插入数据之前,您可以选择是否应将数据粘贴为FIELD。
如果选择了字段,则数据会出现在字段中(例如插入日期/时间时),右键单击字段并在上下文菜单中选择“更新字段”,数据应自动更新。这不起作用,因为Word再次提示数据源,因此无法实现基于不需要用户交互的SQL查询的报告。
VBA(并且通过vba进行创建表和填写单元格的手工劳动)是实现零用户交互的唯一方法吗?
答案 0 :(得分:0)
您可以通过各种方式实现此结果:
选择的选项取决于我能想到的一些变量:
当您提供更多背景或文档应该是什么样的示例时,我可以进一步确定选项吗?
答案 1 :(得分:0)
感谢大家的意见。我最后写了这个VBA:
Private Sub Document_Open()
'wipe the document
Selection.WholeStory
Selection.Delete
'prepare drivers
Dim cn As New ADODB.connection
Dim rs As New ADODB.recordset
'setup document header
ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text = "CRONUS AB - All employees report"
ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Style = "Title"
'prepare header for table
Selection.TypeText "First name" & vbTab & "Last name" & vbTab & "Job title" & vbCrLf
'create connection and execute SQL query
cn.Open "DRIVER={SQL Server};SERVER=localhost;" & _
"trusted_connection=yes;DATABASE=Demo Database NAV (5-0)"
rs.Open "SELECT * FROM [CRONUS Sverige AB$Employee]", cn
'iterate through recordset and print out results to the document
Do While Not rs.EOF
Firstname = rs![First Name]
Lastname = rs![Last Name]
Jobtitle = rs![Job Title]
Selection.TypeText Firstname & vbTab
Selection.TypeText Lastname & vbTab
Selection.TypeText Jobtitle & vbCrLf
rs.MoveNext
Loop
'convert text to table and apply table style
ActiveDocument.Range.ConvertToTable Separator:=wdSeparateByTabs
ActiveDocument.Tables(1).Style = "Light Shading"
End Sub