如何在Excel的每个工作表中搜索特定列

时间:2015-04-05 06:21:57

标签: excel excel-vba vba

我有一个包含50多个工作表的excel文档,所有工作表都有类似的命名约定。 由于这对用户导航到如此不友好,我编写了一个VBA宏,它创建了一个名为summary的工作表,其中所有工作表的列表都以表格形式进行了超链接,其中Sheet AB和C为Column,Sheet 1和2为行

现在我正在尝试遍历Sheet 1和Sheet 2中特定列的每一行,并查找对SheetB,SheetC和SheetD的任何引用,并查找找到的每个引用,并且我想标记创建矩阵。

我不知道如何实现这一目标。任何帮助将不胜感激。

我设法搜索工作表1和2以获取对SheetB的任何引用,如下所示,但我不知道如何在摘要表中更新相应的单元格。

Function findWord(word As String, wSheet As String) As Boolean

    Dim LastRow As Long
    Dim i As Long
    LastRow = Worksheets(wSheet).Cells(Rows.Count, "D").End(xlUp).Row

    For i = LastRow To 1 Step -1
       If Worksheets(wSheet).Range("D" & i).Value = word Then
          findWord = True
          Exit Function
       End If
    Next i
End Function


For Each wsSheet In wbBook.Worksheets
    If (wsSheet.Name <> wsActive.Name) And (Left(wsSheet.Name, 4) <>   "fact") Then
    For i = 2 To lastColumn
         MsgBox wsSheet.Name
       If findWord(columnNames(counter2), wsSheet.Name) Then
          'Update summary sheet
       End If
       counter = counter2 + 1
    Next i

End If
Next wsSheet

1 个答案:

答案 0 :(得分:1)

如果您要查找的“摘要表”中的结果与此类似:
Table on Summary sheet

然后你可以使用这样的东西(阅读代码中的注释以获得解释)

Sub MarkReferencesToSheets()

    Dim wsSummary As Worksheet 'sheet with summary table matrix
    Dim wsSheetRow As Worksheet 'sheets in which we will search references to other sheets
    Dim strSheetColumnName As String 'name of the reference we are looking for
    Dim intSheetRow As Integer 'for loop purposes
    Dim intSheetColumn As Integer 'for loop purposes

    Set wsSummary = Sheets("Summary")

    For intSheetRow = 2 To 3 'change to suit; headers for rows in summary sheet
        Set wsSheetRow = Worksheets(wsSummary.Cells(intSheetRow, 1).Value)
        For intSheetColumn = 2 To 4 'change to suit; headers for columns in summary sheet
            strSheetColumnName = wsSummary.Cells(1, intSheetColumn) 'name of sheet we are looking for
            If Not wsSheetRow.Columns(4).Find(strSheetColumnName) Is Nothing Then 'look only in column "D", or 4
                wsSummary.Cells(intSheetRow, intSheetColumn) = "X" ' if we found it, mark it
            Else
                'if you want something else in the cell when reference is not found, put it here
            End If
        Next intSheetColumn
    Next intSheetRow

End Sub