1

我在 Access 数据库中链接了表。我想与其他用户共享这个数据库和相关的 Excel 工作簿。我想编写一个一次性使用宏,用户第一次使用数据库时将使用该宏将链接表重新链接到新用户的本地文件夹。

例如:

链接表当前正在从以下位置提取文件:
C:\Users\jane.doe\Desktop\Database Imports\Premier Account List.xlsx

当新用户(假设他们的名字是 John Smith)重新链接表时,它需要读取:C:\Users\john.smith\Desktop\Database Imports\Premier Account List.xlsx

我基本上想将文件路径从我的操作系统用户名更改为新用户的操作系统用户名。我已经有了提取操作系统用户名的代码,但我不确定如何编写代码来更改文件路径。这是提取操作系统用户名的代码:

Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Function fOSUserName() As String

' Returns the network login name
Dim lngLen As Long, lngX As Long
Dim strUserName As String

strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)

If (lngX > 0) Then
    fOSUserName = Left$(strUserName, lngLen - 1)
Else
    fOSUserName = vbNullString
End If

End Function

我对 VBA/Access 还很陌生,所以如果你的答案尽可能具体,那就太好了。先谢谢了!

4

1 回答 1

0

TableDef 对象有一个您需要更改的 Connect 属性。这是一个读/写字符串。您只需要一些字符串操作即可使其成为您想要的样子。请注意,如果他们将数据库文件移动到相同的路径,您可以直接拉取CurrentProject.Path而不是使用用户名 API。

Sub ChangeTableLink()

    Dim sNewPath As String
    Dim lDbaseStart As Long
    Dim td As TableDef
    Dim sFile As String
    Dim db As DAO.Database

    'This is what we look for in the Connect string
    Const sDBASE As String = "DATABASE="

    'Set a variable to CurrentDb and to the table
    Set db = CurrentDb
    Set td = db.TableDefs("Fuel Pricing")

    'Whatever your new path is, set it here
    sNewPath = CurrentProject.Path & "\"

    'Find where the database piece starts
    lDbaseStart = InStr(1, td.Connect, sDBASE)

    'As long as you found it
    If lDbaseStart > 0 Then
        'Separate out the file name
        sFile = Dir(Mid(td.Connect, lDbaseStart + Len(sDBASE), Len(td.Connect)))

        'Rewrite Connect and refresh it
        td.Connect = Left(td.Connect, lDbaseStart - 1) & sDBASE & sNewPath & sFile
        td.RefreshLink
    End If

End Sub
于 2015-06-24T21:19:38.587 回答