Search code examples
excelvbaautomationworksheet

Move Worksheet based off a cell value to another workbook


I'm hoping someone can help with this but I'm having the darnest time getting anything to work. I have a rather large workbook with lots of worksheets, I have a report that runs and populates Column B with a "trigger" Column A: is the name of all the worksheets in the workbook. Column B is the indicator that the specific worksheet needs to be moved, e.g. "Yes". I need to move the specified workbook into another workbook.

I can only find applicable examples for moving cells but it didn't work. Any help or direction will be greatly appreciated!

Dim WBK As Workbook
Dim WBK2 As Workbook 
Set WBK= ThisWorkbook
Set WBK= Workbooks.Open(Filename:"ReportList.xlsx") 
For i = 1 To Sheets("MoveSheet").End(xlDown).Row '(ERRORHERE)
   If Sheets("MoveSheet").Range("B" & i) = "Move" Then 
       Sheets(Sheets("MoveSHeet").Range("A" & i)).Move After:=wkbk2.Sheets(1)
   Else
 End if
Next i 
End Sub

Solution

  • Your posted code is not too far off - a few typos etc

    Try this:

    Sub Tester()
    
        Dim wb As Workbook, wsList As Worksheet, c As Range
        Dim wbDest As Workbook
        
        Set wb = ThisWorkbook
        Set wsList = wb.Worksheets("MoveSheet") 'your sheet with tab names and "Move" flag
        
        Set wbDest = Workbooks.Open(Filename:="C:\Example\Path\ReportList.xlsx") 'provide the full path
        
        For Each c In wsList.Range("A1:A" & wsList.Cells(Rows.Count, "A").End(xlUp).Row).Cells
            If c.Offset(0, 1).Value = "Move" Then  'has a flag to be moved?
                wb.Worksheets(c.Value).Move after:=wbDest.Sheets(wbDest.Sheets.Count) 'move after last sheet
            End If
        Next c
        
    End Sub