|
'函数名称:LinkSQLServerTable
'作 用:根据表名和SQL Server服务IP地址,在ACCESS中创建SQL SERVER链接表
'作 者:杨恒
'优 化:陈友福 QQ86053924 欢迎大家和我交流。
'优化日期:2017-11-29
'优化内容:将sub过程修改为函数、增加了对已有链接表的删除、添加了1个判断表在ACCESS中是否存在的通用函数
'参数说明:LinkSQLServerTable("表1,表2,表3,表n", "IP,端口号", "数据库名称", "用户名", "密码")
'调用实例:If LinkSQLServerTable("tblTest,tblTT","127.0.0.1,,1433","DataTest","sa","wd123") Then MsgBox "链接成功
'以下代码:在Access2016+SQL Server2014中测试通过
Public Function LinkSQLServerTable(ByVal strTableNames As String, ByVal IP As String, ByVal strDataBaseName As String, ByVal strUID As String, Optional ByVal strPwd As String = "") As Boolean
Dim dbs As DAO.Database
Dim tdf As TableDef
Dim strConnect As String
Dim arr As Variant
Dim ar As String
Dim i As Long
Dim strSourceTableName As String
ar = strTableNames '要链接的SQL Server数据库表名
arr = Split(ar, ",")
For i = LBound(arr) To UBound(arr)
Set dbs = CurrentDb
strConnect = "ODBC;DRIVER=SQL Server;SERVER=" & IP & ";DATABASE=" & strDataBaseName & ";UID=" & strUID & "WD=" & strPwd
Set tdf = dbs.CreateTableDef(arr(i)) '创建链接表,命名为arr(i)
tdf.Connect = strConnect
strSourceTableName = arr(i) 'SQL源表
tdf.SourceTableName = strSourceTableName
If ExisobjTdsTable(strSourceTableName) Then dbs.TableDefs.Delete strSourceTableName '删除存在的链接表
dbs.TableDefs.Append tdf
Set dbs = Nothing
Set tdf = Nothing
Application.RefreshDatabaseWindow '刷新Access
Next
LinkSQLServerTable = True
Set dbs = Nothing
Set tdf = Nothing
End Function
'在Access中,根据表名检查表是否存在
Public Function ExisobjTdsTable(ByVal strTableName As String) As Boolean
Dim objTds As TableDefs
Dim objTd As TableDef
Set objTds = CurrentDb.TableDefs
For Each objTd In objTds
If objTd.Name = strTableName Then
ExisobjTdsTable = True
GoTo Exit_Func
End If
Next
Exit_Func:
Set objTds = Nothing
Set objTd = Nothing
End Function
|
|