1

Getting control variable in use for this, I guess because of "ws", can someone help how to fix? Thanks

Sub CreateNewWBS()
    Dim wbThis As Workbook
    Dim wbNew As Workbook
    Dim ws As Worksheet
    Dim strFilename As String
    Set wbThis = ThisWorkbook
    For Each ws In wbThis.Worksheets
        strFilename = wbThis.Path & "/" & ws.Name
        ws.Copy
        Set wbNew = ActiveWorkbook
        For Each ws In wbNew.Worksheets
            ws.Cells.Copy
            ws.Cells.PasteSpecial xlPasteValues

        wbNew.SaveAs strFilename
        wbNew.Close
    Next ws
End Sub
7
  • 3
    Dim ws2 as Worksheet and use that instead? Also you're missing a Next. Commented Jul 29, 2020 at 16:18
  • 2
    I do not understand the purpose of wbThis? Surely, it is just ThisWorkbook, which will not (and literally can not) change during the macro execution? Commented Jul 29, 2020 at 16:30
  • @Chronocidal I guess just to differentiate between wbNew. The code is working without the Copy Paste Values portion. Commented Jul 29, 2020 at 16:39
  • @BigBen Can I get guidance how to "Set" wb2 before the Copy Paste Value portion? Commented Jul 29, 2020 at 16:40
  • 1
    I proposed ws2 and you don't Set anything. For Each ws2 in wbNew.Worksheets, ws2.Cells.Copy, ws2.Cells.PasteSpecial xlPasteValues. Commented Jul 29, 2020 at 16:49

2 Answers 2

2

Used ws2 and fixed Next statements, works now:

Sub CreateNewWBS()
Dim wbThis As Workbook
Dim wbNew As Workbook
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim strFilename As String
Set wbThis = ThisWorkbook
For Each ws In wbThis.Worksheets
    strFilename = wbThis.Path & "/" & ws.Name
    ws.Copy
    Set wbNew = ActiveWorkbook
        For Each ws2 In wbNew.Worksheets
            ws2.Cells.Copy
            ws2.Cells.PasteSpecial xlPasteValues
        Next
    wbNew.SaveAs strFilename
    wbNew.Close
Next ws
End Sub
Sign up to request clarification or add additional context in comments.

Comments

1

Here is a simplified version of your code:

Sub CreateNewWBs()
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        ws.Copy
        With ActiveWorkbook
            .Worksheets(1).UsedRange.Value = .Worksheets(1).UsedRange.Value
            .SaveAs ThisWorkbook.Path & "/" & ws.Name
            .Close
        End With
    Next ws
End Sub

I have removed the second For loop, which was causing you issues (both because you had For without Next, and because you were trying to reuse an existing variable) on the basis that wbNew only ever contained 1 worksheet, replaced wbThis with ThisWorksheet, and swapped the .Copy:.PasteSpecial with .Value=.Value to avoid needing the clipboard.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.