首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将单元格值放入数组时获取VBA运行时错误

将单元格值放入数组时获取VBA运行时错误
EN

Stack Overflow用户
提问于 2012-09-28 09:51:37
回答 3查看 967关注 0票数 0

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

不过,我有两个问题-

  1. 我在行Run-time error 9 - Subscript out of range上得到了一个错误titles(i) = cell.Value
  2. 我不知道在If语句中有一个行可以用来检查数组中是否存在一个值。

到目前为止这是我的密码。任何关于如何解决这些问题的建议,或者关于可能更好的方法的建议,都将被学习。谢谢。

代码语言:javascript
运行
复制
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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-09-28 10:01:13

试试下面的代码:

代码语言:javascript
运行
复制
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
票数 3
EN

Stack Overflow用户

发布于 2012-09-28 10:01:11

因为您试图在初始化数组之前分配一个值,所以您会得到该错误。

代码语言:javascript
运行
复制
Dim titles() As String
i = 0
For Each cell In title_range
    titles(i) = cell.Value
    '
    '
Next
票数 2
EN

Stack Overflow用户

发布于 2012-09-28 09:57:34

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

此外,您还可以使用LBoundUBound检查边界。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12637665

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档