This commit is contained in:
xiaochou164 2023-08-15 19:19:31 +08:00
parent 777ec3ebc0
commit 3752ee4c3a
2 changed files with 42 additions and 0 deletions

37
DatabaseConn.vba Normal file
View File

@ -0,0 +1,37 @@
'----关闭数据库连接,释放资源
Public Sub closeConn()
On Error Resume Next
If conn Is Nothing Then Exit Sub
conn.Close
Set conn = Nothing
End Sub
'----连接数据库,创建结果集对象
Public Sub AutoRun()
Call closeConn
On Error Resume Next
Dim strDBinf As String
Application.StatusBar = "正在连接数据库……"
If conn Is Nothing Then
Set conn = New ADODB.Connection
Set RES = CreateObject("ADODB.Recordset")
strDBinf = "DSN=mysqlinklexcel32" '标准语句
Call conn.Open(strDBinf)
If VBA.Err.Number <> 0 Then
strDBinf = "DSN=mysqlinklexcel64" '标准语句
VBA.MsgBox "32位DSN连接失败,尝试使用mysqllinkexcel6连接!"
Call conn.Open(strDBinf)
End If
If VBA.Err.Number > 1 Then
VBA.MsgBox "连接异常,请检查DB环境!"
Set conn = Nothing
End If
Application.StatusBar = "数据库连接成功"
End If
End Sub

5
Public.vba Normal file
View File

@ -0,0 +1,5 @@
Public conn As ADODB.Connection '-----定义数据库连接 Public 方便每个SUB使用 不需要重复定义
Public RES As ADODB.Recordset '-----定义结果集 结果集和二维表很类似
Public Sign As String
Dim row, col As Integer
Dim Sql As String