简体   繁体   English

Excel VBA-动态范围

[英]Excel VBA - Dynamic Range

I have a list of numbers on a sheet that needs to be added to an array but in batches. 我在一张纸上有一个数字列表,需要将其分批添加到数组中。 So I have list of 150 or so numbers on List, that needs to get added to an array but in batches of 5. Each new batch will be used to query a SQL database. 因此,我在List上有150个左右的数字列表,需要将其添加到数组中,但要以5的批次添加。每个新批次将用于查询SQL数据库。

The list can change length and will not be even, could be 20 could be 541. 该列表可以更改长度,并且不会是偶数,可能是20可能是541。

Edit: This seems to do what I need but I am sure there is a better solution. 编辑:这似乎可以满足我的需要,但我相信有更好的解决方案。

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

Try, 尝试,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM