可以使用以下代码在EXCEL上使用VBA连接MYSQL数据库 :
Dim strconnt As Stringstrconnt = ""
Set connt = New ADODB.Connection
Dim sevip, Db, user, pwd As String
'设服务器地址、所连数据,及登录用户密码
sevip = "localhost"
Db = “test"
user = "root"
pwd = "123456"
strconnt = "DRIVER={MySql ODBC 5.3 Unicode Driver}SERVER=" & sevip & "Database=" & Db & "Uid=" & user & "Pwd=" & pwd & "Stmt=set names GBK"
connt.ConnectionString = strconnt
connt.Open
要通过EXCEL查询指定数据库中的含 有指定字段的表名时,首先得知道查询SQL,查询SQL如下:
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME='字段名'
如果要写成VBA的话,下面给你一段我写的宏,测试过了:
-----------
Sub 宏7()
' 宏7 宏
Application.CutCopyMode = False
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBCDRIVER=SQL ServerSERVER=服务器IPUID=saAPP=Microsoft Office 2016WSID=GUESSDATABASE=要查询的数据库名" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array( _
"SELECT TABLE_NAME" & Chr(13) & "" & Chr(10) & "FROM 要查询的数据库名.INFORMATION_SCHEMA.COLUMNS" & Chr(13) & "" & Chr(10) & "WHERE (COLUMN_NAME='要查询的字段名')")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
Dim chars As String
Dim rndstr As String
chars = "ABCDEFGHJKLMNPQRSTUVWXYZ0123456789"
Randomize
For i = 1 To 6
rndstr = rndstr & Mid(chars, Int(Rnd() * Len(chars) + 1), 1)
Next
.ListObject.DisplayName = rndstr
.Refresh BackgroundQuery:=False
End With
End Sub
最后结果如下图:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)