Skip to content

Instantly share code, notes, and snippets.

@jspraul
Created July 19, 2012 19:18
Show Gist options
  • Save jspraul/3146116 to your computer and use it in GitHub Desktop.
Save jspraul/3146116 to your computer and use it in GitHub Desktop.
Merge multi-column ranges in Excel
' Licensed under the Apache License, Version 2.0 (the "License"); you may not
' use this file except in compliance with the License. You may obtain a copy of
' the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
' WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
' License for the specific language governing permissions and limitations under
' the License.
' TODO: All columns compared
' TODO: Skip dupes within a single source range
' TODO: Merge arbitrary number of ranges
' TODO: Don't require input be sorted
' Copy two ranges (both sorted by first column) to a new destination
' Skips duplicate rows in the second source that exist in the first
' Only compares the first column
' Stops processing the range when the first column is empty
' Dupes in a range will be duped in the result
Sub MergeRangesOnFirstColumn()
Dim source(2) As Range
Set source(1) = Sheet1.Range("a1:g13")
Set source(2) = Sheet2.Range("a1:g14")
Dim dest As Range
Set dest = Sheet3.Range("a1:z99")
Dim sourceRow(2) As Integer
Dim destRow As Integer
sourceRow(1) = 1
sourceRow(2) = 1
destRow = 1
Do
If sourceRow(1) <= source(1).Rows.Count And source(1).Cells(sourceRow(1), 1) <> "" Then
If sourceRow(2) <= source(2).Rows.Count And source(2).Cells(sourceRow(2), 1) <> "" Then
If source(1).Cells(sourceRow(1), 1) <= source(2).Cells(sourceRow(2), 1) Then
If source(1).Cells(sourceRow(1), 1) = source(2).Cells(sourceRow(2), 1) Then
sourceRow(2) = sourceRow(2) + 1
End If
Call CopyRow(source(1), sourceRow(1), dest, destRow)
Else
Call CopyRow(source(2), sourceRow(2), dest, destRow)
End If
Else
Call CopyRow(source(1), sourceRow(1), dest, destRow)
End If
ElseIf sourceRow(2) <= source(2).Rows.Count And source(2).Cells(sourceRow(2), 1) <> "" Then
Call CopyRow(source(2), sourceRow(2), dest, destRow)
Else
Exit Do
End If
Loop
End Sub
' Bad form: Updates source and dest row offsets!
Sub CopyRow(ByRef source As Range, ByRef sourceRow As Integer, ByRef dest As Range, ByRef destRow As Integer)
For srcC = 1 To source.Columns.Count
dest.Cells(destRow, srcC) = source.Cells(sourceRow, srcC)
Next
sourceRow = sourceRow + 1
destRow = destRow + 1
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment