数据未上传到MS SQL数据库。

时间:2017-08-29 14:32:51

标签: sql-server excel vba

我正在尝试在Excel工作表中按下一个按钮,它应该将数据从工作表发送到sql表。但是这个vba代码没有将数据从excel上传到数据库。我有类似的其他表,它工作正常。对此的任何建议或想法都会很棒。

Sub Send2SQL()

yarn start

2 个答案:

答案 0 :(得分:0)

当您在Execute对象上使用Recordset时,您在Execute上使用Command

答案 1 :(得分:0)

从Excel到SQL Server?试试这种方式。

Sub Rectangle1_Click()
'TRUSTED CONNECTION
    On Error GoTo errH

    Dim con As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim strPath As String
    Dim intImportRow As Integer
    Dim strFirstName, strLastName As String

    Dim server, username, password, table, database As String


    With Sheets("Sheet1")

            server = .TextBox1.Text
            table = .TextBox4.Text
            database = .TextBox5.Text


            If con.State <> 1 Then

                con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
                'con.Open

            End If
            'this is the TRUSTED connection string

            Set rs.ActiveConnection = con

            'delete all records first if checkbox checked
            If .CheckBox1 Then
                con.Execute "delete from tbl_demo"
            End If

            'set first row with records to import
            'you could also just loop thru a range if you want.
            intImportRow = 10

            Do Until .Cells(intImportRow, 1) = ""
                strFirstName = .Cells(intImportRow, 1)
                strLastName = .Cells(intImportRow, 2)

                'insert row into database
                con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')"

                intImportRow = intImportRow + 1
            Loop

            MsgBox "Done importing", vbInformation

            con.Close
            Set con = Nothing

    End With

Exit Sub

errH:
    MsgBox Err.Description
End Sub

我的设置看起来像这样。

enter image description here

另外....... Excel VBA - 更新SQL Server表: http://www.cnblogs.com/anorthwolf/archive/2012/04/25/2470250.html

http://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm

...更多 http://www.ozgrid.com/forum/showthread.php?t=169953

http://stackoverflow.com/questions/2567150/excel-vba-sql-data

http://msgroups.net/microsoft.public.excel.programming/vba-to-export-large-tables/61433

http://www.codeproject.com/Questions/475817/Howplustoplusupdateplussqlplusserverplusdataplusfr

http://www.excelguru.ca/forums/showthread.php?992-SQL-Select-Insert-Update-queries-from-Excel-vba

http://www.mrexcel.com/forum/excel-questions/617303-updating-records-access-table-using-excel-visual-basic-applications.html

http://www.excelforum.com/excel-programming-vba-macros/501147-how-to-use-vba-to-update-a-sql-server-table-from-a-spreadsheet.html