使用access vba连接到sql server

时间:2014-05-06 14:29:22

标签: sql sql-server ms-access access-vba

大家好,我花了几天时间研究如何使用vba连接SQL服务器,并发现微软有关如何设置无DSN连接的有趣帖子,他们提供了代码,这就是它的样子。 / p>

'//Name :AttachDSNLessTable
'//Purpose:Create a linked table to SQL Server without using a DSN 
'//stLocalTableName: Name of the table that you are creating in the current database
'//stRemoteTableName: Name of the table that you are linking to on the SQL Server
'//database
'//stServer: Name of the SQL Server that you are linking to
'//stDatabase: Name of the SQL Server database that you are linking to
'//stUsername: Name of the SQL Server user who can connect to SQL Server, leave blank
'//to use a Trusted Connection
'//stPassword: SQL Server user password

Function AttachDSNLessTable(stLocalTableName As String, stRemoteTableName As String,       stServer As String, stDatabase As String, Optional stUsername As String,       Optional stPassword As String)
On Error GoTo AttachDSNLessTable_Err
Dim td As TableDef
Dim stConnect As String

For Each td In CurrentDb.TableDefs
    If td.Name = stLocalTableName Then
        CurrentDb.TableDefs.Delete stLocalTableName
    End If
Next

If Len(stUsername) = 0 Then
    '//Use trusted authentication if stUsername is not supplied.
    stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & stServer & ";DATABASE=" & stDatabase & ";Trusted_Connection=Yes"
Else
    '//WARNING: This will save the username and the password with the linked table information.
    stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & stServer & ";DATABASE=" & stDatabase & ";UID=" & stUsername & ";PWD=" & stPassword
End If
Set td = CurrentDb.CreateTableDef(stLocalTableName, dbAttachSavePWD, stRemoteTableName, stConnect)
CurrentDb.TableDefs.Append td
AttachDSNLessTable = True
Exit Function

AttachDSNLessTable_Err:

AttachDSNLessTable = False
MsgBox "AttachDSNLessTable encountered an unexpected error: " & Err.Description

End Function


Private Sub Form_Open(Cancel As Integer)
If AttachDSNLessTable("authors", "authors", "(local)", "pubs", "", "") Then
    '// All is okay.
Else
    '// Not okay.
End If
End Sub

我的问题是这个代码有效,但它对我不起作用,因为如果我把这个表单交给别人,他们将无法打开它,因为事件是在Form_open中设置的,你无法打开除非您已有数据表,否则请填写表单。在打开表单之前,我是否可以使用更好的事件功能来创建无DSN连接?

如果我尝试在没有设置DSN的情况下打开表单,这是我收到的错误"此表单或报表上指定的记录源不存在。"

以下是我使用方法1的源http://support.microsoft.com/kb/892490的链接。

2 个答案:

答案 0 :(得分:2)

如果此代码适合您,但您需要一个更好的地方来执行它/一个将执行的地方与该表单的定义无关,您可以在AutoExec宏中运行它。

AutoExec宏是一个名为AutoExec的宏,它在您启动Access应用时运行。您可以使用RunCode宏函数来调用您的VBA函数(它必须是函数而不是子函数)。

这样,您甚至可以在表单打开之前(重新)链接您的表。

答案 1 :(得分:0)

打开一个空白表单,将固定数据记录作为源。运行您的代码,然后根据您的要求将源表单更改为您的真实表单(OPEN FORM操作中的VBA代码)。这是SMOKE和MIRROW代码。你将有一次地狱调试它。