diff --git a/DatabaseConn.vba b/DatabaseConn.vba new file mode 100644 index 0000000..8d5f81b --- /dev/null +++ b/DatabaseConn.vba @@ -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 \ No newline at end of file diff --git a/Public.vba b/Public.vba new file mode 100644 index 0000000..bbef538 --- /dev/null +++ b/Public.vba @@ -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 \ No newline at end of file