使用Nexted for循环遍历工作表中的所有单元格和工作簿中的所有工作表

时间:2018-07-20 02:00:51

标签: excel vba excel-vba

我正在尝试更新工作簿中所有工作表上的记录。 我的搜索值在第6列中,替换值在第9列中

该代码一次仅适用于一个工作表,而不一次适用于整个工作表。

我在下面尝试过,但这给我一个错误

Sub AllWorksheetsLoop()
    Dim WS_Count As Integer
    Dim I As Integer
    ' Set WS_Count equal to the number of worksheets in the active
    ' workbook.
    WS_Count = ActiveWorkbook.Worksheets.count

    ' Begin the loop.
    For I = 1 To WS_Count
        Dim N As Long
        Dim count As Long

        N = Cells(Rows.count, 1).End(xlUp).Row
        For count = 1 To N
            v1 = Cells(count, 6).Value
            If v1 = "Palm Tree (M)" Then Cells(count, 9).Value = "='Project Comp Rate Akwa Ibom'!K7"
        Next count
    Next I
End Sub

请协助

1 个答案:

答案 0 :(得分:1)

听起来您想要类似的内容,在每个工作表的F列中搜索"Palm Tree (M)";如果找到,则在同一行的右侧3列中的单元格中输入所述公式。我假设您不搜索公式中引用的工作表。

Option Explicit
Public Sub FindThatPhrase()
    Application.ScreenUpdating = False
    Dim ws As Worksheet, found As Range
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> "Project Comp Rate Akwa Ibom" Then
            Set found = GetAllMatches("Palm Tree (M)", ws.Columns("F"))
            If Not found Is Nothing Then
                Debug.Print ws.Name, found.Address
                found.Offset(, 3) = "='Project Comp Rate Akwa Ibom'!$K$7"
            End If
        End If
    Next ws
Application.ScreenUpdating = True
End Sub

Public Function GetAllMatches(ByVal findString As String, ByVal searchRng As Range) As Range

    Dim foundCell As Range
    Dim gatheredRange As Range

    With searchRng

        Set foundCell = searchRng.Find(findString)
        Set gatheredRange = foundCell

        Dim currMatch As Long

        For currMatch = 1 To WorksheetFunction.CountIf(.Cells, findString)

            Set foundCell = .Find(What:=findString, After:=foundCell, _
                                  LookIn:=xlValues, Lookat:=xlWhole, SearchOrder:=xlByRows, _
                                  SearchDirection:=xlNext, MatchCase:=False)

            If Not gatheredRange Is Nothing Then
                Set gatheredRange = Union(gatheredRange, foundCell)
            Else
                Set gatheredRange = foundCell
            End If

        Next currMatch

    End With

    Set GetAllMatches = gatheredRange

End Function