0

I'm trying to find out if a value exists in a range of cells and, if not, run a function. I am using Excel 2007.

I have two problems however -

  1. I'm am getting an error Run-time error 9 - Subscript out of range on the line titles(i) = cell.Value.
  2. I'm unaware of a one liner that can be used in an If statement to check if a value exists in an array.

Here is my code so far. Any pointers on how to solve these problems, or tips on approaches that maybe better, would be grately apprciated. Thanks.

Sub start()

    Dim title_range As Range        ' The range that contains the column titles
    Dim cell As Range               ' The individual cell from the title range
    Dim titles() As String          ' The column titles
    Dim i As Integer                ' Dummy for count

    ' Set the column titles range
    Set title_range = ActiveWorkbook.Sheets("DJG Marketing - Client List by ").Range("A1:DZ1")
    i = 0
    For Each cell In title_range
        titles(i) = cell.Value
        i = i + 1
        ReDim Preserve titles(i)
    Next

    If {value 'Matter open month' does not exist in the array `titles`} Then
        create_month_column
    End If

End Sub
Community
  • 1
  • 1
David Gard
  • 11,225
  • 36
  • 115
  • 227

3 Answers3

3

Try this code:

i = 0
ReDim titles(i) 'this is missing ;)
For Each cell In title_range
    titles(i) = cell.Value
    i = i + 1
    ReDim Preserve titles(i)
Next
Jook
  • 4,564
  • 3
  • 26
  • 53
2

You are getting that error because you are trying to assign a value before initializing the array

Dim titles() As String
i = 0
For Each cell In title_range
    titles(i) = cell.Value
    '
    '
Next
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
0

Doesn't VBA starts with Index 1 in Arrays?

Besides that, you can always check the bounds with LBound and UBound.

321X
  • 3,153
  • 2
  • 30
  • 42
  • 1
    in vba you have always to specify your array bounds, so it is up to you. But as Siddarth pointed out, David used a dynamic array and did not initialize it, so it had no bounds at all. – Jook Sep 28 '12 at 10:08