Excel VBA-动态范围

时间:2019-01-22 17:16:18

标签: sql excel vba loops

我在一张纸上有一个数字列表,需要将其分批添加到数组中。因此,我在List上有150个左右的数字列表,需要将其添加到数组中,但要以5的批次添加。每个新批次将用于查询SQL数据库。

列表可以更改长度,并且不会是偶数,可能是20,可能是541。

编辑:这似乎可以满足我的需要,但我确信有更好的解决方案。

Dim i As Integer

Sheets("List").Select
lRow = Cells(Rows.Count, 1).End(xlUp).Row

Range("a1").Select


For i = 1 To lRow

    begrng = ActiveCell.Address
    ActiveCell.Offset(4, 0).Select
    endrng = ActiveCell.Address


    Set rng = Range(begrng, endrng)


    For Each cell In rng
        If Not IsEmpty(cell) Then
        mystring = mystring & "','" & cell.Value
        End If
    Next cell

    mystring = Right(mystring, Len(mystring) - 2)
    mystring = ""

Next

End Sub

1 个答案:

答案 0 :(得分:0)

尝试

Dim i As Long, lRow As Long, mystring As String, ayes As Variant

With Worksheets("List")

    lRow = .Cells(.Rows.Count, "A").End(xlUp).Row

    For i = 1 To lRow Step 5

        ayes = Application.Transpose(.Range(.Cells(i, "A"), .Cells(i + 4, "A")).Value2)

        mystring = Application.Trim(Join(ayes, Space(1)))
        ayes = Split(mystring, Space(1))
        mystring = Chr(39) & Join(ayes, "','") & Chr(39)

        Debug.Print mystring

    Next i
End With