Excel中的VBAmacros来运行SQL插入语句

嗨,我很新的VBA,我希望有人能帮我最后一点的代码。

我试图从电子表格中取出单元格并将它们添加到SQL表中,但是我正在运行SQL语句。 这是我到目前为止的代码。

Private Sub ConnectDB() Dim oConn As Object Set oConn = CreateObject("ADODB.Connection") oConn.Open = "DRIVER={SQL Server};" & _ "SERVER=SERVER02;" & _ "DATABASE=platform;" & _ "USER=5y5t3mus3r;" & _ "PASSWORD=*******;" & _ "Option=3;" If oConn.State = adStateOpen Then MsgBox "Welcome to Database!" Else MsgBox "Sorry No Database Access." End If Dim rs As ADODB.Recordset Dim strSQL As String Dim Company As String Dim Address As String Dim Address1 As String Dim Address2 As String Dim County As String Dim Contact As String Dim Phone As String Dim Fax As String strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _ & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";" Sheets("wsheet").Activate Set rs = New ADODB.Recordset rs.Source = Sql With wsheet MyFile = "C:\Users\Ryan.ICS\Documents\Documents\InsertStatement.txt" fnum = FreeFile() Open MyFile For Output As fnum myRow = 2 myCol = 4 For myRow = 2 To InputBox(Prompt:="What is the last row of data?", Title:="Data Row", Default:=1) myCol = 4 Company = ActiveSheet.Cells(myRow, myCol) myCol = myCol + 1 Address = ActiveSheet.Cells(myRow, myCol) myCol = myCol + 1 Address1 = ActiveSheet.Cells(myRow, myCol) myCol = myCol + 1 Address2 = ActiveSheet.Cells(myRow, myCol) myCol = myCol + 1 Address3 = ActiveSheet.Cells(myRow, myCol) myCol = myCol + 2 Phone = ActiveSheet.Cells(myRow, myCol) myCol = myCol + 1 Fax = ActiveSheet.Cells(myRow, myCol) myCol = myCol + 1 strSQL = "INSERT INTO [sandbox].[5y5t3mus3r].[ryan] (Organisation, Address1, Address2, TownCity, County, Telephone, Fax) VALUES('" & Company & "', '" & Address & "', '" & Address1 & "', '" & Address2 & "', '" & Address3 & "', " & Phone & ", " & Fax & ");" Print #fnum, strSQL DoCmd.RunSQL strSQL ***Here is where I am haveing an error it will not run the SQL command.**** oConn.Execute strSQL **** here is another tag I tried in a number of different ways but i still couldnt get the SQL statement to run Next End With ' Find out how many rows were affected by the Insert. Set rs = oConn.Execute("Select @@rowcount") ' Display the first field in the recordset. MsgBox rs(0) & " rows inserted" oConn.Close Set rs = Nothing Set oConn = Nothing Close #fnum End Sub Function esc(txt As String) esc = Trim(Replace(txt, "'", "\'")) End Function 

当我尝试运行SQL语句时出现错误,我需要为此创build一个对象或方法。

任何帮助,这将非常感谢,谢谢!

我猜这是这一行:

rs.Source = Sql

Source属性接受一个I​​Stream以及一个string,因为Sql没有在任何地方声明,所以它隐含的是一个值为Nothing的对象。

我的下一个猜测是在下面几行,wsheet分配在哪里?

当然,如果我们知道错误发生在哪一行,所有这一切将会变得更加容易…如果您设置了一个断点并进入代码 – 您不需要将variables值转储到文件,您可以查看他们交互在debugging器中。

我build议使用ADOBO.Command对象创build一个存储过程并将值传递给它,而不是使用INSERT语句。

看这篇文章

使用ADO将数据从Excel导入到SQl是一种简单的方法。

[]的

Interesting Posts