简体   繁体   中英

Excel VBA - SQL Query and Field Mappings

I have created an excel spreadsheet used for calculating shipping rates based on miles using an add-in for =GetGoogleDistance to do the calculations. Since you are limited to just 2500 querys a day without paying for it, I elected to save the results from searches that have been done into my SQL database. I have everything working as planned so far except for pulling the data back from SQL and mapping the fields correctly. What I am after is say I have Distance1 field within my SQL database, how do I map it to ActiveWorkbook.Sheets("Southwest Miles Shipper").Range("D8") and it populate the field. The only way I have gotten the data to come out is just in a row format, I can take that data from there and do VBA work to get it to the proper places, but I wanted to check and see if anyone knows how to do it. Here is a link to the current file:

I think all you need to do is modify your getGoogleDistance method to:

  1. Check SQL Server to see if the value already exists
  2. If it does, return that value -- no call to Google
  3. If it doesn't, run your normal function and then insert that value into SQL Server

As far as how to do steps #1 and #3, there is no shortage of examples if you know where to look. If you search ADO, SQL Server, VBA I think will see more examples than you can shake a stick at. As an alternative to Step 1, you can also use MS Query, which is built into MS Excel, and that would eliminate some VBA, but it doesn't preclude you from having to use ADO since there is nothing built-in (that I know of) to manage the inserts.

This is a really bare-bones (and untested) example of how you could do the insert:

Dim conn As ADODB.Connection
Dim cmd As New ADODB.Command
Dim cs As String

Set conn = New ADODB.Connection

cs = "Provider=SQLOLEDB;Data Source=<whatever>\<whatever>;" & _
     "Initial Catalog=<whatever>;" & _
     "Integrated Security=SSPI;"

conn.ConnectionString = cs

cmd = New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandText = "insert into [Distances] values (@FROM, @TO, @DIST)"
cmd.NamedParameters = True

cmd.Parameters.Append cmd.CreateParameter("@FROM", adVarChar, adParamInput, 256, fromValue)
cmd.Parameters.Append cmd.CreateParameter("@TO", adVarChar, adParamInput, 256, toValue)
cmd.Parameters.Append cmd.CreateParameter("@DIST", adNumeric, adParamInput, 256, distance)

cmd.Execute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM