VBA Export Excel to SQL Item cannot be found in th

2019-07-29 06:51发布

I am trying to automate the export of an Excel file to SQL Server. The code is good (been checked by a few people) and the table in SQL Server and the Excel file is the exam same. (I imported an Excel flat file in SQL Server and then delete all rows and now I am trying to import in that same table)

Sub testexportsql()
Dim cn As ADODB.connection
Dim ServerName As String
Dim DatabaseName As String
Dim TableName As String
Dim UserID As String
Dim Password As String
Dim rs As ADODB.recordset
Dim RowCounter As Long
Dim NoOfFields As Integer
Dim StartRow As Long
Dim EndRow As Long
Dim ColCounter As Integer

Set rs = New ADODB.recordset

ServerName = "xxx" ' Enter your server name here
DatabaseName = "xxx" ' Enter your  database name here
TableName = "dbo.AlbertaData_import" ' Enter your Table name here
UserID = "xxx" ' Enter your user ID here
' (Leave ID and Password blank if using windows Authentification")
Password = "xxx" ' Enter your password here
NoOfFields = 331 ' Enter number of fields to update (eg. columns in your worksheet)
StartRow = 2 ' Enter row in sheet to start reading  records
EndRow = 200 ' Enter row of last record in sheet

 '  CHANGES
Dim shtSheetToWork As Worksheet
Set shtSheetToWork = ActiveWorkbook.Worksheets("Sheet2")
 '********

Set cn = New ADODB.connection

cn.Open "Driver={SQL Server};Server=" & ServerName & ";Database=" & DatabaseName & _
";Uid=" & UserID & ";Pwd=" & Password & ";"

rs.Open TableName, cn, adOpenKeyset, adLockOptimistic

 'EndRow = shtSheetToWork.Cells(Rows.Count, 1).End(xlUp).Row
For RowCounter = StartRow To EndRow
    rs.AddNew
    For ColCounter = 1 To NoOfFields
    'On Error Resume Next
        rs(ColCounter - 1) = shtSheetToWork.Cells(RowCounter, ColCounter)
    Next ColCounter
    Debug.Print RowCounter
Next RowCounter
rs.UpdateBatch

 ' Tidy up
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing

End Sub

Run-time error '3265'

Item cannot be found in the collection corresponding to the request name or cardinal

标签: excel vba
0条回答
登录 后发表回答