2012-09-28 21 views
0

我试图找出一个单元格区域中是否存在值,如果不存在,请运行一个函数。我使用Excel 2007中将单元格值放入数组时将VBA运行时错误

我不过有两个问题 -

  1. 我点上线titles(i) = cell.Value收到错误Run-time error 9 - Subscript out of range
  2. 我不知道可以在If语句中使用的单线程来检查数组中是否存在值。

这是我的代码到目前为止。任何关于如何解决这些问题的指针,或者关于可能更好的方法的提示,都会非常感谢。谢谢。

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 

回答

3

试试这个代码:

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 
+0

+ 1是的:)现货 –

+0

非常感谢,这是第一部分解决。第二部分的任何提示呢? –

+0

@DavidGard:看到这个http://stackoverflow.com/questions/11109832/how-to-find-if-an-array-contains-a-string –

0

不是VBA以索引1开头的数组?

除此之外,你可以随时检查边界LBoundUBound

+1

在VBA你必须总是指定数组边界,所以它是由你决定。但是正如Siddarth指出的那样,David使用了一个动态数组并且没有初始化它,所以它没有任何限制。 – Jook

2

你得到这个错误,因为你正试图初始化阵列之前将值分配

Dim titles() As String 
i = 0 
For Each cell In title_range 
    titles(i) = cell.Value 
    ' 
    ' 
Next 
+0

谢谢,我不知道我必须这样做。 –