VBA如何在上载时跳过特定行

时间:2016-02-23 10:14:48

标签: excel vba

                 **Column 1  Column2  Column 3 Column 4 ETC**

**Row 1**           100        200      330        4000   
**Row 2**           4678       5744     5333       8000

**Row 3**           

**Row 4**           100      120       1600        900 

**Row 5**           

**Row 6**           4477      237       220         3200

**Row 7**

ETC

这是一个示例表。 我想要做的是跳过某些行,因为你可以看到第5行没有数据,所以我不想包含它,但我需要它继续这样我才能获得所有数据第6排,第7排等 我正在从VBA和excel上传数据到SQL。 尝试过If Statement         如果sht.Cells(lRow,1)=""然后是ExitSub

尝试将所有空格更改为Null - 但是其中一些单元格中包含公式,因此没有空值但也无法上传。

我认为这是一个简单的解决方案,我只是遗漏了一些明显的东西。 任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

如果您想跳过该行,但继续使用其余数据,那么您的代码需要

If sht.Cells(lRow, 1) = "" Then lRow = lRow + 1
EndIf

假设这是循环的一部分?如果您可以发布有用的整个VBA代码。

上传我使用的数据的好代码如下:

Sub export_entirexref_to_sql()

Dim conn As New ADODB.Connection
Dim RowNo As Long
Dim i, x As Long
Dim C1, C2, C3, C4 As String
Dim wbk As Workbook
Dim strFile As Variant
Dim shtname As String
Dim strSQL As String
strFile = Application.GetOpenFilename
If strFile = False Then
Exit Sub
Else: End If

Application.ScreenUpdating = False

    ' *** Open workbooks first ***
    Set wbk = Workbooks.Open(strFile)
    shtname = ActiveWorkbook.Worksheets(1).Name
    lastrow = wbk.Sheets(1).Cells(Rows.Count, "A").End(xlUp).Row + 1
    With Sheets(shtname)

    'Open a connection to SQL Server
    conn.Open "Provider=SQLOLEDB;Data Source=xxxxxx\xxxx;Initial Catalog=xxxxx;User ID=xxx; Password=xxxxxx; "

    ' Delete table data
    conn.Execute "TRUNCATE TABLE EcommerceXRefMapping_C_copy;"

    'Skip the header row
    RowNo = 2

    'Loop until empty cell in Col 1
    Do Until .Cells(RowNo, 1) = ""
        i = i + 1
        C1 = .Cells(RowNo, 1)
        C2 = .Cells(RowNo, 2)
        C3 = .Cells(RowNo, 3)
        C4 = .Cells(RowNo, 4)

        'Generate and execute sql statement to import the excel rows to SQL Server table

        strSQL = strSQL + "insert into EcommerceXRefMapping_C_copy ([EquivalentPartNumber_C], [Manufacturer_C], [CatamacPartNumber_C], [Notes_C]) values ('" & C1 & "', '" & C2 & "', '" & C3 & "', '" & C4 & "');"

        conn.Execute strSQL

        RowNo = RowNo + 1

    Loop

    conn.Close
    Set conn = Nothing

    End With

    wbk.Close
    Application.ScreenUpdating = True

End Sub

您只需在此处添加IF语句

        conn.Execute strSQL


        RowNo = RowNo + 1

        If sht.Cells(RowNo, 1) = "" Then RowNo = RowNo + 1
        EndIf

    Loop