我想使用從SQL Server數據庫繪製的數據自動化一些郵件合併功能。以下是我正在使用的代碼:如何使用VBA連接到SQL Server?
Sub open_DSN()
Dim strConnection As String
ActiveDocument.MailMerge.CreateDataSource Name:="DB-NAME", _
Connection:="Provider=SQLOLEDB.1;Persist Security Info=False;Initial Catalog=DB-NAME;Data Source=DATA-SOURCE", _
SQLStatement:="select * from DataTable"
ActiveDocument.MailMerge.OpenDataSource Name:="DB-NAME"
If ActiveDocument.MailMerge.DataSource.Name <> "" Then _
MsgBox ActiveDocument.MailMerge.DataSource.Name
' – code lifted from MS Help within Word that seems the nearest to what I require
'With ActiveDocument.MailMerge
' .MainDocumentType = wdFormLetters
' strConnection = "DSN=MS Access Databases;" _
' & "DBQ=C:\Northwind.mdb;" _
' & "FIL=RedISAM;"
' .OpenDataSource Name:="C:\NorthWind.mdb", _
' Connection:=strConnection, _
' SQLStatement:="SELECT * FROM Customers"
'End With
With ActiveDocument.MailMerge
.MainDocumentType = wdFormLetters
strConnection = "Provider=SQLOLEDB.1;Persist Security Info=False;Initial Catalog=DB-NAME;Data Source=DATA-SOURCE"
.OpenDataSource Name:="DB-NAME", _
Connection:=strConnection, _
SQLStatement:="SELECT * FROM DataTable"
End With
End Sub
不幸的是,我無法獲得該代碼來顯示數據。我究竟做錯了什麼?
RajendraNarine:不客氣。此外,由於您是StackOverflow的新手,我想通知您,您可以通過選中答案旁邊的勾號來接受最能幫助您的答案。 –