0

我试图找出某个值是否存在于一系列单元格中,如果不存在,则运行一个函数。我正在使用 Excel 2007。

但是我有两个问题-

  1. Run-time error 9 - Subscript out of range在线上遇到错误titles(i) = cell.Value
  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
4

3 回答 3

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
于 2012-09-28T10:01:13.770 回答
2

您收到该错误是因为您试图在初始化数组之前分配一个值

Dim titles() As String
i = 0
For Each cell In title_range
    titles(i) = cell.Value
    '
    '
Next
于 2012-09-28T10:01:11.060 回答
0

VBA 不是从数组中的索引 1 开始吗?

除此之外,您始终可以使用LBound和检查边界UBound

于 2012-09-28T09:57:34.210 回答