首页 > 解决方案 > 在 .Find 函数中调用数组元素

问题描述

我有一个包含“n”个字符串的数组,我想在 .find 函数中调用数组中的每个字符串,并在整个工作表中搜索相应的字符串,然后在工作表中显示字符串的位置。

Dim SCtr as long

Dim whattofind as variant

WhatToFind = Array("pdy", "Pdx", "temp")

For SCtr = LBound(WhatToFind) To UBound(WhatToFind)

     'here is the problem it was searching only first value in the array not going to the next item in the array

    Set Cell = Cells.Find(What:=WhatToFind(SCtr), After:=ActiveCell, LookIn:= _
                         xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows,                  SearchDirection:= _xlNext, MatchCase:=False, SearchFormat:=False)

      If Not Cell Is Nothing Then
           'do something
Next SCtr

哪个函数可以用于这个目的,或者可以做些什么来使这个代码工作

标签: excelvba

解决方案


您的代码中缺少一个End If。试试下面的代码,它会将在 Array 中找到字符串的单元格着色为红色。

尝试这个:

Sub colr()

Dim SCtr As Long
Dim whattofind As Variant
Dim cel As Range


whattofind = Array("pdy", "Pdx", "temp")

For SCtr = LBound(whattofind) To UBound(whattofind)

    Set cel = ActiveSheet.Cells.Find(What:=whattofind(SCtr))


    If Not cel Is Nothing Then
        cel.Interior.ColorIndex = 3
    End If

Next SCtr

End Sub

尽量避免 Excel 使用的对象名称。喜欢Cell


推荐阅读