The ClearContents method removes data from cells while preserving formatting. This is different from deleting cells, which shifts surrounding cells.
Private Sub CommandButton1_Click()
Range("A1:A6").ClearContents
End Sub
This clears values from cells A1 through A6.
Private Sub CommandButton1_Click()
Dim selectedRng As String
selectedRng = InputBox("Enter range to clear (e.g., B2:D10)")
If selectedRng <> "" Then
Range(selectedRng).ClearContents
End If
End Sub
Added error handling for when user cancels the input box.
Sub ClearAllData()
Dim response As Integer
response = MsgBox("Clear ALL data in this sheet?", vbYesNo + vbQuestion)
If response = vbYes Then
Sheet1.Cells.ClearContents
MsgBox "Worksheet cleared successfully", vbInformation
End If
End Sub
Safer implementation with confirmation dialog.
ClearFormats removes formatting while keeping cell values intact. Useful for standardizing appearance.
Sub RemoveAllFormatting()
Application.ScreenUpdating = False
Dim ws As Worksheet
Set ws = ActiveSheet
ws.Cells.ClearFormats
ws.Cells.Font.Name = "Calibri"
ws.Cells.Font.Size = 11
Application.ScreenUpdating = True
MsgBox "All formatting cleared. Default font applied.", vbInformation
End Sub
While Select is commonly used, direct range manipulation is often more efficient in VBA.
Sub SelectRangeExamples()
' Basic selection
Range("A1:D10").Select
' Select entire used range
ActiveSheet.UsedRange.Select
' Select current region (contiguous data)
Range("A1").CurrentRegion.Select
' Select with Offset (3 rows down, 2 columns right)
Range("A1").Offset(3, 2).Select
' Select last cell in column A
Cells(Rows.Count, 1).End(xlUp).Select
End Sub
Range("A1").Font.Bold = TrueApplication.ScreenUpdating = False for multiple operations
Sub PrepareDataForAnalysis()
On Error GoTo ErrorHandler
Application.ScreenUpdating = False
Dim ws As Worksheet
Set ws = ActiveSheet
' Clear old data and formatting
ws.Cells.ClearContents
ws.Cells.ClearFormats
' Apply standard formatting
With ws.UsedRange
.Font.Name = "Calibri"
.Font.Size = 11
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlCenter
End With
' Format headers
With Rows(1)
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
Application.ScreenUpdating = True
MsgBox "Data preparation complete!", vbInformation
Exit Sub
ErrorHandler:
Application.ScreenUpdating = True
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical
End Sub
Copyright ® 2008- Dr.Liew Voon Kiong . All rights reserved [Privacy Policy]
Contact: Facebook Page