Excel vba如何向函数传递范围从mysql检索数据

Excel vba如何向函数传递范围从mysql检索数据,excel,vba,Excel,Vba,我编写了一个vba来传递范围的偏移量作为另一个函数的查询表的输入,但我遇到了错误 Sub test2() Dim LastCol As Long With ThisWorkbook.Sheets("Summary (AIX)") LastCol = .Range("A2").SpecialCells(xlCellTypeLastCell).Column End With Dim r As Long Dim ser_name As String Dim y As String For r =

我编写了一个vba来传递范围的偏移量作为另一个函数的查询表的输入,但我遇到了错误

Sub test2()

Dim LastCol As Long
With ThisWorkbook.Sheets("Summary (AIX)")
LastCol = .Range("A2").SpecialCells(xlCellTypeLastCell).Column
End With

Dim r As Long
Dim ser_name As String
Dim y As String

For r = (LastCol - 1) To 2 Step -2
With ThisWorkbook.Sheets("Summary (AIX)")
y = Cells(2 + 2, r + 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

MsgBox CStr(Cells(2, r).Value)
ser_name = CStr(Cells(2, r).Value)
get_unix_avg_cpu ser_name, y
End With
Next r
End Sub
=========================================================================

Sub get_unix_avg_cpu(server_hostname, x)


Dim oRS As ADODB.Recordset
Dim ConnString As String
Dim SQL As String


Dim qt As QueryTable
ThisWorkbook.Sheets(server_hostname).Activate

ConnString = "Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=test;User=root;Password=123456;Option=3;"
Set oCn = New ADODB.Connection
oCn.ConnectionString = ConnString
oCn.Open


SQL = "SELECT cpu_max_unix_0.CPU FROM test.cpu_max_unix cpu_max_unix_0 where cpu_max_unix_0.SERVER_NAME='" & server_hostname & "' Order By cpu_max_unix_0.LOGDATE"

Set oRS = New ADODB.Recordset
oRS.Source = SQL
oRS.ActiveConnection = oCn
oRS.Open

Set qt = ThisWorkbook.Sheets("Summary (AIX)").QueryTables.Add(Connection:=oRS, _
Destination:=ThisWorkbook.Sheets("Summary (AIX)").Range(x))


qt.Refresh

If oRS.State <> adStateClosed Then
oRS.Close
End If


If Not oRS Is Nothing Then Set oRS = Nothing
If Not oCn Is Nothing Then Set oCn = Nothing


End Sub
Sub-get\u unix\u avg\u cpu(服务器主机名,x)
将oRS设置为ADODB.Recordset
将字符串变为字符串
将SQL设置为字符串
将qt设置为查询表
ThisWorkbook.Sheets(服务器名称)。激活
ConnString=“Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=test;User=root;Password=123456;Option=3;”
设置oCn=New ADODB.Connection
oCn.ConnectionString=ConnString
开放式
SQL=“从test.cpu\u max\u unix cpu\u max\u unix\u 0中选择cpu\u max\u unix\u 0.cpu,其中cpu\u max\u unix\u 0.SERVER\u NAME=”“&SERVER\u hostname&“按cpu\u max\u unix\u 0.LOGDATE排序”
Set oRS=新的ADODB.Recordset
oRS.Source=SQL
oRS.ActiveConnection=oCn
开放的
Set qt=thiswook.Sheets(“摘要(AIX)”).QueryTables.Add(连接:=oRS_
目标:=ThisWorkbook.Sheets(“摘要(AIX)”).Range(x))
qt.刷新
如果oRS.State已关闭,则
好的,结束
如果结束
如果不是oRS,则设置oRS=Nothing
如果不是oCn为Nothing,则设置oCn=Nothing
端接头
在“Sub get_unix_avg_cpu(服务器主机名,x)”上停止 编译错误:未定义用户定义的类型


请帮忙

ADODB是一个外部库,这意味着它没有内置到Excel中,所以您需要将它添加到您的项目中

为此,在IDE中单击工具>引用

然后向下滚动,直到找到“MicrosoftActiveX数据对象”,其中会有一些对象,因此选择数字最大的一个,勾选它,然后按ok

然后,您应该能够运行代码


这种方法称为早期绑定,为了让您的工作簿为其他人工作,他们也需要在他们的计算机上安装此参考。通常,在开发时,最好使用代码将在其上运行的库的最低版本。您也可以使用后期绑定。

是否添加了对Microsoft Active Data Objects库的引用?