通过VBA将值插入到SQL Server表中
假设我在Excel中有两个表(Name,Rate)(比如这个表的名字是tExcel
)。 表从单元格(2,1)开始,并且date是静态的(在单元格(1,1)中)
我想用下面的逻辑将这些值插入到SQL Server 2008 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
我创build了一个连接
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
感谢帮助。
编辑到@jaimetotal答案
sql= "insert tRate(ID, Rate, Date) SELECT s.ObjectId ," & Replace(Row.Cells(2).Value, ",", ".") & ",'" & defaultDate & "' FROM tSecurity s where s.number = '" & row.Cells(1).Value & "'; "
对于这个示例,我假设tExcel.Number是第一列,tExcel.Rate是第二列。 这里的想法是对表(或范围)中的每一行执行一个操作,并创build一个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
编辑:如果你真的是一个表,比你可以从这里使用这个样本。
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