You can use the HorizontalAlignment and VerticalAlignment properties in VBA to center the text in specific cells in Excel horizontally and vertically, respectively.
Here are three common ways to use these properties in practice:
Method 1: Center Text Horizontally Using VBA
Sub CenterText()
Range("A2:A11").HorizontalAlignment = xlCenter
End Sub
Method 2: Center Text Vertically Using VBA
Sub CenterText()
Range("A2:A11").VerticalAlignment = xlCenter
End Sub
Method 3: Center Text Both Horizontally & Vertically Using VBA
Sub CenterText()
Range("A2:A11").HorizontalAlignment = xlCenter
Range("A2:A11").VerticalAlignment = xlCenter
End Sub
The following examples show how to use each method in practice with the following dataset in Excel:
Example 1: Center Text Horizontally Using VBA
We can create the following macro to center the text in each cell in the range A2:A11 horizontally:
Sub CenterText()
Range("A2:A11").HorizontalAlignment = xlCenter
End Sub
When we run this macro, we receive the following output:
Notice that the text in each cell in the range A2:A11 has been centered horizontally.
Example 2: Center Text Vertically Using VBA
We can create the following macro to center the text in each cell in the range A2:A11 vertically:
Sub CenterText()
Range("A2:A11").VerticalAlignment = xlCenter
End Sub
When we run this macro, we receive the following output:
Notice that the text in each cell in the range A2:A11 has been centered vertically.
Example 3: Center Text Both Horizontally & Vertically Using VBA
We can create the following macro to center the text in each cell in the range A2:A11 both horizontally and vertically:
Sub CenterText()
Range("A2:A11").HorizontalAlignment = xlCenter
Range("A2:A11").VerticalAlignment = xlCenter
End Sub
When we run this macro, we receive the following output:
Notice that the text in each cell in the range A2:A11 has been centered both horizontally and vertically.
Additional Resources
The following tutorials explain how to perform other common tasks in VBA:
VBA: How to Change Font Color
VBA: How to Make Font Bold
VBA: How to Replace Characters in String