使用宏VBA将Excel中的200,000行导入SQL

时间:2016-10-06 22:35:40

标签: sql excel excel-vba rows vba

通过宏将信息从Excel传递到SQL时出现问题。

运行宏时,文件开始上传行,但突然停止并出现以下错误"溢出(6)"这使得每个32676行都得到了处理。

起初我以为这是记录中的内容,但是当我返回执行时,句子重新开始并在记录32676上再次停止,

我尝试上传超过200,000行的Excel文件,每条记录包含25列。

我可能会因为这件事而做错事。

我分享交易代码。

Private Sub CommandButton1_Click()
Dim conn As New ADODB.Connection
conn.CommandTimeout = 0
    Dim iRowNo As Integer
    Dim PK_ID As String, CUST_ID As Long, DOC_TYPE As String, BILL_DOC As Long, REFERENCE As String, INV_CON As String, ORDER_SALER As String, INV_REF As String, DOC_NUM As Long, GL As Long, DOC_DATE As Double, DUE_DATE As Double, ECURRENCY As String, DOC_AMNT As Currency, USD_AMNT As Currency, PAY_TERM As String



    With Sheets("ONREPSAP")

        'Abrimos conexion con el SQL server
        conn.Open "Provider=SQLOLEDB;Data Source=,1433;Initial Catalog=AmericanMovil;User ID=;Password=;Encrypt=True;"

        'Omitimos la linea de encabezados
        iRowNo = 2

        'Loop until empty cell in CustomerId
        Do Until .Cells(iRowNo, 1) = ""
            PK_ID = .Cells(iRowNo, 1)
            CUST_ID = .Cells(iRowNo, 2)
            DOC_TYPE = .Cells(iRowNo, 3)
            BILL_DOC = .Cells(iRowNo, 4)
            REFERENCE = .Cells(iRowNo, 5)
            INV_CON = .Cells(iRowNo, 6)
            ORDER_SALES = .Cells(iRowNo, 7)
            INV_REF = .Cells(iRowNo, 8)
            DOC_NUM = .Cells(iRowNo, 9)
            GL = .Cells(iRowNo, 10)
            DOC_DATE = .Cells(iRowNo, 11)
            DUE_DATE = .Cells(iRowNo, 12)
            ECURRENCY = .Cells(iRowNo, 13)
            DOC_AMNT = .Cells(iRowNo, 14)
            USD_AMNT = .Cells(iRowNo, 15)
            PAY_TERM = .Cells(iRowNo, 16)



            'Generamos y ejecutamos la QUERY SQL para importar las lineas de excel a SQL
            conn.Execute "insert into dbo.ONREPSAP (PK_ID, CUST_ID, DOC_TYPE, BILL_DOC, REFERENCE, INV_CON, ORDER_SALES, INV_REF, DOC_NUM, GL, DOC_DATE, DUE_DATE, ECURRENCY, DOC_AMNT, USD_AMNT, PAY_TERM) values ('" & PK_ID & "', '" & CUST_ID & "', '" & DOC_TYPE & "', '" & BILL_DOC & "', '" & REFERENCE & "', '" & INV_CON & "', '" & ORDER_SALES & "', '" & INV_REF & "', '" & DOC_NUM & "', '" & GL & "', '" & DOC_DATE & "', '" & DUE_DATE & "', '" & ECURRENCY & "', '" & DOC_AMNT & "', '" & USD_AMNT & "', '" & PAY_TERM & "')"

            iRowNo = iRowNo + 1
        Loop

        MsgBox "Reporte Cargado Correctamente | The report has finish to Uploading"


        conn.Close
        Set conn = Nothing

    End With
End Sub

在Debug中,VBA在"循环"

之前选择iRowNo + 1

1 个答案:

答案 0 :(得分:2)

正如@Comintem所说,你需要改变类型来保持更大的价值。

您应该声明Dim iRowNo As Long而不是Integer

Here数据类型摘要

Integer uses 2 bytes and Range from -32,768 to 32,767
Long    uses 4 bytes and Range from -2,147,483,648 to 2,147,483,647