You are here:

Excel/Help with VBA runtime error


QUESTION: Hello. I have a simple VBA macro that merges rows together if they have duplicate rows in the first column. It worked fine last month, and now all of a sudden it says "runtime error 9: subscript out of range'."

Can you help?

Sub MergeRows()
   Dim rng As Range
   Dim vSrc As Variant
   Dim vDst() As Variant
   Dim i As Long, j As Long

   ' Assumes data starts at cell A2 and extends down with no empty cells
   Set rng = Range([A2], [A2].End(xlDown))

   ' Count unique values in column A
   j = Application.Evaluate("SUM(IF(FREQUENCY(" _
       & rng.Address & "," & rng.Address & ")>0,1))")
   ReDim vDst(1 To j, 1 To 2)
   j = 1

   ' Get original data into an array
   vSrc = rng.Resize(, 2)

   ' Create new array, one row for each unique value in column A
   vDst(1, 1) = vSrc(1, 1)
   vDst(1, 2) = "'" & vSrc(1, 2)
   For i = 2 To UBound(vSrc, 1)
       If vSrc(i - 1, 1) = vSrc(i, 1) Then
         vDst(j, 2) = vDst(j, 2) & "," & vSrc(i, 2)
         j = j + 1
         vDst(j, 1) = vSrc(i, 1)
         vDst(j, 2) = "'" & vSrc(i, 2)
       End If


   ' Remove old data

   ' Put new data in sheet
   Set rng = [A2].Resize(j, 2)
   rng = vDst

End Sub

ANSWER: Hi Martin,

On which line does the error occur?

---------- FOLLOW-UP ----------

QUESTION: Oops sorry.

It highlights this line in debug mode:

  ReDim vDst(1 To j, 1 To 2)

Looks like j is less than 1. In a ReDim statement, the first index size must always be less than or equal to the second.


ReDim vDst(1 To 1, 1 To 2)

is valid


ReDim vDst(1 To 2, 1 To 2)

is valid


ReDim vDst(1 To 0, 1 To 2)

is not.
About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here


All Answers

Answers by Expert:

Ask Experts


Jan Karel Pieterse


Excel and Excel/VBA questions


Excel MVP

Self employed Excel developer

Bachelor in Chemical Engineering

Awards and Honors
Microsoft MVP award since 2002

Past/Present Clients
Shell, Fortis bank, ABN-AMRO bank, Morgan Stanley, ...

©2017 All rights reserved.