Excel VBA Code to Convert Formulas to Values

 

Sub ConvertToValues()
On Error GoTo ErrorHandler

Dim r As Range

If ActiveSheet.ProtectContents Then ‘Need This?
MsgBox “This Worksheet is Protected”, vbOKCancel + vbDefaultButton1, “Unable to Proceed”
Exit Sub
End If

If ActiveWindow.SelectedSheets.Count > 1 Then
MsgBox “Cannot Perform on Multiple Sheets”, vbOKCancel + vbDefaultButton1, “Unable to Proceed”
Exit Sub
End If

If Selection.Cells.CountLarge = Cells.CountLarge Then ‘If user selected entire sheet, just grabs Used Range
ActiveSheet.UsedRange.Select
End If

Application.Calculate ‘Do this before converting to values

‘This isn’t needed
‘ If Application.CalculationState xlDone Then ‘Is File Done Calculating?
‘ MsgBox “File Is Not Done Calculating”, vbOKCancel + vbDefaultButton1, “Results”
‘ Exit Sub
‘ End If

‘ Speed Optimization
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False ‘Note this is a sheet-level setting

‘ Selection.Value = Selection.Value ‘This is supposed to be faster than copy & paste. Will error if a cell has huge number of characters.

For Each r In Selection ‘This is far faster than Selection.Value = Selection.Value
r = r.Value
Next r

‘ Re-activate the screen
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.Calculation = xlAutomatic
Application.EnableEvents = True
ActiveSheet.DisplayPageBreaks = True

Exit Sub

ErrorHandler:
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.Calculation = xlAutomatic
Application.EnableEvents = True
ActiveSheet.DisplayPageBreaks = True
MsgBox Err.Description, vbOKCancel + vbDefaultButton1, “Error Number: ” & Err.Number
End Sub