通过VBA将值插入SQL Server表

时间:2015-08-24 14:21:15

标签: excel vba excel-vba

假设我在Excel中有一个表,其中包含两列(Name,Rate)(例如,此表的名称为a< b >)。表从单元格(2,1)开始,日期是静态的(在单元格(1,1)中)

我想将这些值插入到SQL Server 2008 tExcel表中,并带有以下逻辑

tRate

我已经创建了一个连接

insert tRate(ID, Rate, Date)
   select 
       s.ObjectID, e.Rate, Date   -- date comes from cell(1,1). DateType is smalldatetime
   from 
      tExcel e, tSecurity s
   where 
      e.Name = s.Number

感谢您的帮助。

编辑@jaimetotal回答

Sub disp_cust()
Dim adoCN As ADODB.Connection
Dim sConnString As String
Dim sSQL As String
Dim lRow As Long, lCol As Long
Set cn = New ADODB.Connection
sConnString = "Provider=sqloledb;Server=xxx;Database=xxx;User Id=xxx;Password=xxx"
Set adoCN = CreateObject("ADODB.Connection")
adoCN.Open sConnString
adoCN.Close
Set adoCN = Nothing
End Sub

1 个答案:

答案 0 :(得分:2)

对于此示例,我假设tExcel.Number是第一列,tExcel.Rate是第二列。这里的想法是为表(或范围)中的每一行执行a并创建一个insert / select语句。

Dim rng as Range
Dim defaultDate As string
Dim sql as string, bulkSql as string

Set rng = Range("A1:XX") -- Range of the table. 
defaultDate = Format(Range("A2").Value, "yyyy/mm/dd") 
bulkSql = ""  

'generated sample: insert tRate(ID, Rate, Date) SELECT s.ObjectId, '0.15', '2015/08/24' FROM tSecurity s where s.Number = '007'

For Each row In rng.Rows

    sql= "insert tRate(ID, Rate, Date) SELECT s.ObjectId " & "','" & row.Cells(2).Value & "','" & defaultDate & "' FROM tSecurity s where s.number = '" & row.Cells(1).Value & "'; "

    bulkSql = bulkSql & sql  

Next row

adoCn.Execute bulkSql, , adCmdText

修改 如果你真的是指一张桌子,那么你可以使用基于here的这个样本。

Dim lo As Excel.ListObject
Dim ws As Excel.Worksheet
Dim lr As Excel.ListRow

Set ws = ThisWorkbook.Worksheets(1)
Set lo = ws.ListObjects("tExcel")

'The other code from the previous sample. Use the following ForEach instead

For Each lr In lo.ListRows
   Dim Rate as String
   Dim Number as String

   Rate = Intersect(lr.Range, lo.ListColumns("Rate").Range).Value
   Number = Intersect(lr.Range, lo.ListColumns("Number").Range).Value

   'Generate the query from these values instead   

Next lr