Jonathan
Jonathan

Reputation: 47

VBA (Excel): Looped copy on multiple criteria in multiple worksheets

Background
I have a master file which holds many sheets of data, and I have a list of requested changes which is constantly being updated. I need to write a macro such that it will run down each row in the Changes sheet and find its counterpart within the actual data sheets. I need to copy the relevant cells from the change sheet to the respective row where it exists in its particular sheet.

Information

Here's my attempt so far, I have a feeling it's pretty off but I hope the logic at least makes sense. I am attempting to run through each row in the Changes sheet, search through all the Sheets (A, B, C, ... L) for LOBID, then for CourseCode. When a matching pair is found, I'm hoping to copy the value from the changeWS to the matched cell in the datasheet (there are many values to copy but I've left them out for code brevity). It doesn't throw any errors but it doesn't seem to do anything at all. If someone could at least nudge me in the right direction, I'd appreciate it.

Upvotes: 3

Views: 777

Answers (1)

Tim Williams
Tim Williams

Reputation: 166511

Compiled but not tested:

Sub InputChanges()

    Dim changeWS As Worksheet, rw As Range
    Dim i As Integer

    Set changeWS = ActiveWorkbook.Sheets("Changes")

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

    For i = 4 To changeWS.Range("A" & Rows.Count).End(xlUp).Row

        Set rw = GetRowMatch(CStr(changeWS.Cells(i, 2)), CStr(changeWS.Cells(i, 5)))
        If Not rw Is Nothing Then
            rw.Cells(1, "AP").Value = changeWS.Cells(i, 24).Value
            changeWS.Cells(i, 2).Interior.Color = vbGreen
        Else
            changeWS.Cells(i, 2).Interior.Color = vbRed
        End If

   Next i

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

End Sub

Function GetRowMatch(LOBID As String, CourseCode As String) As Range
    Dim arrSheets, s, sht As Worksheet, rv As Range, f As Range
    Dim addr1 As String
    arrSheets = Array("Sheet A", "Sheet B", "Sheet C") ', etc.")
    For Each s In arrSheets
        Set s = ActiveWorkbook.Sheets(s)
        Set f = s.Columns(1).Find(LOBID, Cells(Rows.Count, "A"), xlValues, xlWhole)
        If Not f Is Nothing Then
            addr1 = f.Address()
            Do
                If f.EntireRow.Cells(5) = CourseCode Then
                    Set GetRowMatch = f.EntireRow 'return the entire row
                    Exit Function
                End If
                Set f = s.Columns(1).Find(LOBID, f, xlValues, xlWhole)
            Loop While f.Address() <> addr1
        End If
    Next s
    'got here with no match - return nothing
    Set GetRowMatch = Nothing
End Function

Upvotes: 1

Related Questions