Option Compare Database
Option Explicit
Public Function AttachExcel( _
ByVal sFileName As String, _
ByVal sTablename As String, _
ByVal sRangeName As String _
) As Boolean
Const conCannotOpen = 3432
Const conNotRange = 3011
Const conTableExists = 3012
Dim db As DAO.Database
Dim td As DAO.Tabledef
Dim sConnect As String
Dim sMsg As String
Dim sFunction As String
On Error GoTo HandleError
AttachExcel = False
sFunction = "AttachExcel"
' Check for existence of worksheet:
sFileName = CurDir() & "\" & sFileName
' If the file isn't found, notify
' the user and exit the procedure:
If Len(Dir(sFileName)) = 0 Then
MsgBox "The file " & sFileName _
& " could not be found"
MsgBox "Please move the file to " _
& CurDir() & " to continue"
Exit Function
End If
Set db = CurrentDb
' Create a new tabledef in the current database:
Set td = db.CreateTableDef(sTablename)
' Build connect string:
sConnect = "Excel 8.0;HDR=YES;DATABASE=" & sFileName
td.Connect = sConnect
' Specify Range Name sRangeName:
td.SourceTableName = sRangeName
' Append new linked table to TableDefs collection:
db.TableDefs.Append td
'Return True:
AttachExcel = True
ExitHere:
Exit Function
HandleError:
Select Case Err
Case conCannotOpen
sMsg = "Cannot open " & sFileName
Case conTableExists
sMsg = "The table " & sTablename & _
" already exists."
Case conNotRange
sMsg = "Can't find the " & sRangeName & " range."
Case Else
sMsg = "Error#" & Err & ": " & Error$
End Select
MsgBox sMsg, vbExclamation + vbOKOnly, _
"Error in Procedure " & sFunction
'Return False:
AttachExcel = False
Resume ExitHere
End Function
这是链接Excel文件的函数,红色代码中的语句如何理解?
另外sourcename和定义中的stablename 是不是一回事?