Consulting

Results 1 to 7 of 7

Thread: Sleeper: Merge dynamic array list

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    VBAX Newbie
    Joined
    Apr 2005
    Posts
    3
    Location

    Question Sleeper: Merge dynamic array list

    Hi

    Please can someone help me, I am new to VBA. I have a program that merges 2 lists into one. I am trying to change it into a dynamic array. I have started to but I get stuck with the for loop.

    Below is the code.

    Sub MergeLists()
        Dim List1() As String, List2() As String
        Dim List3() As String
        Dim Index1 As Integer, Index2 As Integer, Index3 As Integer
        Dim Name1 As String, Name2 As String
        Dim NI As Integer
        'For loop variable
        Dim i As Integer
        ' With Range("A4")
            ' NI = Range(.Offset(1, 0), .End(xlDown)).Rows.Count
            ' End With
            'Copy Customer name into array list 1 and list 2
            For i = 1 To 93
                List1(i) = Range("A5").Cells(i)
            Next i
            For i = 1 To 102
                List2(i) = Range("B5").Cells(i)
            Next i
            'Initialise index for ist 1 and List 2
            Index1 = 1
            Index2 = 1
            'Implete merge algorit
            Do While (Index1 <= 93) And (Index2 <= 102)
                Name1 = List1(Index1)
                Name2 = List2(Index2)
                Index3 = Index3 + 1
                ReDim Preserve List3(Index3)
                If Name1 < Name2 Then
                     List3(Index3) = Name1
                     Index1 = Index1 + 1
                ElseIf Name1 > Name2 Then
                     List3(Index3) = Name2
                     Index2 = Index2 + 1
                Else
                    List3(Index3) = Name1
                    Index1 = Index1 + 1
                Index2 = Index2 + 1
            End If
        Loop
        'copy remaining names lseft in List 1 to List 3
        For i = Index1 To 93
              Index3 = Index3 + 1
              ReDim Preserve List3(Index3)
              List3(Index3) = List1(i)
         Next i
        'copy any remaining names left in list 2 to list 3
         For i = Index2 To 102
              Index3 = Index3 + 1
              ReDim Preserve List3(Index3)
              List3(Index3) = List2(i)
        Next i
        ' Using For loop copy each name into merged list 3 to column D of worksheet
        With Range("D4")
              For i = 1 To Index3
                  .Offset(i, 0).Value = List3(i)
              Next i
         End With
         'Place curser in cell A2
         Range("A2").Select
    End Sub
    Last edited by Aussiebear; 12-21-2024 at 11:57 AM. Reason: Adding VBA Tags

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •