使用Excel VBA查找范围

时间:2009-11-18 12:05:13

标签: excel vba

我已经获得了一些针对眼睛而不是任何功能的工作簿。因此,我有很多列标题如下:

  A             B         C         D      E
1               'YTD      'Monthly  'YTD   'Monthly
2               Figures'  Figures'  Plan'  Plan'
3  
4  Account1     1         3         5      7
5  Account2     2         4         6      8

我一直在做的是使用.Find标识'Account 1'的行,然后标识'Monthly Plan'的列标题,并将该单元格值复制到数组中。但是,有几个区域(例如我上面的示例)我无法轻松找到E列,因为搜索'Monthly''Plan'显然会给我带来不可靠的结果。

到目前为止,我一直在使用Do... While... Loop来查找'Monthly'的单元格地址,然后检查紧邻下方的单元格值'Plan',并使用{{1}进行循环直到有匹配。

这不是很优雅 - 所以有没有办法可以搜索我正在寻找的单词排列的虚拟数组/范围?

1 个答案:

答案 0 :(得分:1)

如果您发现一个单元格和下一个单元格的串联怎么办?

您可以通过修剪或删除空格,符号以及将所有内容转换为小写来简化它,以便于检测。

不应使用find,而应循环使用单元格。

编辑:这是一个可能的解决方案:

Sub Macro1()

    Dim idx_row As Long
    Dim idx_column As Long
    Dim idx_row_temp As Long
    Dim found_row As Boolean
    Dim found_column As Boolean
    Dim str_concat As String

    found_row = False
    idx_row = 1
    idx_column = 1
    Do While (Not found_row)
        If (Cells(idx_row, idx_column).Value = "Account1") Then
            found_row = True
        Else
            idx_row = idx_row + 1
        End If
    Loop

    found_column = False
    idx_row_temp = 1
    Do While (Not found_column)

        str_concat = Cells(idx_row_temp, idx_column).Value & Cells(idx_row_temp + 1, idx_column).Value

        MsgBox (str_concat)

        If (str_concat = "'MonthlyPlan'") Then
            found_column = True
        Else
            idx_column = idx_column + 1
        End If
    Loop

    MsgBox "Row: " & idx_row & vbCrLf & "Column: " & idx_column

End Sub

当然可以改进和改进,但这是基本的想法。

或者......为什么你找不到第一个数值?