如何在excel中通过宏来直接取得数据库中的数据?

我想请教一下,如何在excel中通过宏来直接取得数据库中的数据?
最新回答
睡着的未来

2024-12-01 01:52:24

这个很简单,代码如下:

Sub C5C15_B3B13()
Dim Fo As Object, myName As String
Set Fo = Application.FileDialog(msoFileDialogFilePicker)
Fo.Title = "请选择您要复制C5:C15数据的文件:"
If Fo.Show = True Then myName = Fo.SelectedItems(1)
If myName = "" Then
MsgBox "您取消了文件选择,所以本次处理未完成,将直接退出", vbOKOnly + vbInformation
Exit Sub
End If

Dim wb as Workbook
For Each wb in Workbooks
if wb.Fullname = myName then Goto wbHasOpened
Next
set wb = workbooks.open(myname)
wbHasOpened:

Dim sh as worksheet
For each sh in wb.sheets
if sh.name = "Voice Quality" Then
[b3:B13] = sh.[c5:c15].value
Exit For
end if
Next
Msgbox "处理完成!"
wb.close True
End Sub
与君醉笑三千场

2024-12-01 01:49:57

Sub shujuchengji()
'实现读取数据写入数据库
Dim SqlStr, str As String
Dim EndRow As Integer

'str = CurDir(ThisWorkbook.FullName) 表示当前文件夹,你可以选择用
str = "c:\1.mdb" ' 你数据库的路径
Dim Con As New ADODB.Connection
On Error GoTo err:
Con.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & str

SqlStr = "" '里面是sql语句
Con.Execute SqlStr

Con.Close
MsgBox "导入成功"
Exit Sub
err:
MsgBox "数据连接错误"

End Sub