自定义函数来查询MYSQL

时间:2016-12-02 09:01:00

标签: mysql excel vba excel-vba

我还没有接触过VBA或mySQL。我试图创建一个自定义函数来查询mysql表并将结果放入Excel中。

该表包含CompanyName,Date和发票价格。过去,他们使用Excel表并使用vlookups /过滤器来尝试缩小它,但他们在Excel表格中获得了大约30年的数据,迟早,它会在将要休息。

我已经让他们使用以下sql查询到mysql数据库 -

select * from StockManagement.Deliveries where CompanyName = "SupplierCode" and DATE BETWEEN "StartDate" and "EndDate"    

但是,现在他们希望将此作为=getinvoices(SupplierCode, Start Date, End Date)之类的函数使用,并为此填充表格的3个标题,公司名称,日期,发票金额

的Excel工作表

代码我已设法串联起来以使ODBC驱动程序正常工作,它实际上是在拉取数据如下所示。我只需要把它变成一个有变量的函数。

Sub MySQLtoExcel()

Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset

Server_Name = "localhost" ' Enter your server name here
Database_Name = "StockManagement" ' Enter your database name here
User_ID = "root" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM StockManagment.Deliveries where CompanyName = 'ABC LTD' and DATE BETWEEN '2016-11-23' '2016-11-25';"

Set Cn = New ADODB.Connection
Cn.Open "Driver={MySQL ODBC 5.3 ANSI Driver};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"

rs.Open SQLStr, Cn, adOpenStatic
' Dump to spreadsheet
With Worksheets("Sheet1").Range("a1:g500")
    .ClearContents
    .CopyFromRecordset rs
End With
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub

0 个答案:

没有答案