Search code examples
arraysexcelvbacopyformula

VBA Copy sheets to new workbook - with/without formulas


I use this code to copy 4 sheets to separate workbook. One of them - "1" have formulas inside, method below skips those formulas. Any ideas how to keep three workbook's as value only and one - "1" including the formulas? Part of code responsible for that action below. Thank you in advance.

Sub test()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim Fname As String, ws As Worksheet
Dim InitFileName As String, fileSaveName As String
Fname = Sheets("STRUCTURE").Range("A1").Value
Sheets(Array("STRUCTURE", "2", "3", "1")).Copy
For Each ws In ActiveWorkbook.Worksheets
    With ws.UsedRange
        .Value = .Value
    End With
Next ws
With ActiveWorkbook
fileSaveName = "FILE LOCATION FOLDER " & Sheets("STRUCTURE").Cells(1, 1) & ".xlsx"
    .SaveAs fileSaveName
    .Close
End With

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

Solution

  • This is what is changing formulas to values:

    With ws.UsedRange
        .Value = .Value
    End With
    

    You have several options to skip the worksheet in question:

    1. Skip the worksheet named 1.
    For Each ws In ActiveWorkbook.Worksheets
        If ws.Name <> "1" Then
            With ws.UsedRange
                .Value = .Value
            End With
       End If
    Next
    
    1. Only loop over the worksheets in question:
    Dim sheetNamesToProcess As Variant
    sheetNamesToProcess = Array("STRUCTURE", "2", "3")
    
    Dim i As Long
    For i = Lbound(sheetNamesToProcess) To Ubound(sheetNamesToProcess)
        With ActiveWorkbook.Worksheets(sheetNamesToProcess(i)).UsedRange
            .Value = .Value
        End With
    Next