Access开发培训
网站公告
·Access专家课堂QQ群号:151711184    ·Access快速开发平台下载地址及教程    ·欢迎加入Access专家课堂微信群!    ·如何快速搜索本站文章|示例|资料    
您的位置: 首页 > 技术文章 > Access数据库-模块/函数/VBA

根据表名和SQL Server服务IP地址,在ACCESS中创建SQL SERVER链接表

时 间:2017-11-29 17:42:19
作 者:smileyoufu   ID:1784  城市:成都
摘 要:根据表名和SQL Server服务IP地址,在ACCESS中创建SQL SERVER链接表
正 文:

'函数名称: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","Pwd123") 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 & ";PWD=" & 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


Access软件网QQ交流群 (群号:54525238)       Access源码网店

常见问答:

技术分类:

相关资源:

专栏作家

关于我们 | 服务条款 | 在线投稿 | 友情链接 | 网站统计 | 网站帮助