Adjusting Center Across Selection with a Cell Value

Written by Allen Wyatt (last updated March 31, 2021)
This tip applies to Excel 2007, 2010, 2013, and 2016


8

Jean likes using the "Center Across Selection" setting on the Alignment tab of the Format Cells dialog box to center information across un-merged cells. She wonders, though, if there is a way she can use the contents of one cell to control across how many cells the centering occurs. For instance, if she has the number 4 in cell A1, then the centering would be across 4 cells (B1:E1), but if she changes it to 5 then the centering would be across 5 cells (B1:F1).

The only way this can be done is through the use of a macro. Because you might change the value in cell A1, the macro needs to run whenever you make a change to the workbook and then determine if that change was made in cell A1 or not. If so, then it can make the adjustment to the cells in the row.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim sWidth As String
    Dim sStartCell As String
    Dim iWidth As Integer
    Dim r As Range
    Dim sTemp As String

    sWidth = "$A$1"
    sStartCell = "$B$1"

    If Target.Address = sWidth Then
        iWidth = Range(sWidth).Value
        If iWidth > 1 Then
            sTemp = Right(sStartCell, 1)
            sTemp = sTemp & ":" & sTemp
            Range(sTemp).HorizontalAlignment = xlGeneral

            Set r = Range(sStartCell)
            Set r = r.Resize(1, iWidth)
            r.HorizontalAlignment = xlCenterAcrossSelection
        End If
    End If
End Sub

Note that this macro is placed in the code sheet for the worksheet you want to affect. Whenever a change is made in the worksheet, the macro automatically runs. In order to make it work for you, you should change the addresses assigned to the sWidth and sStartCell variables. sWidth is set to the cell that contains how many columns you want to center across. sStartCell is set to the first cell at the left of the range where the centering is to occur.

The macro grabs whatever is in your sWidth cell and places it in the iWidth variable. If this value is greater than 1, then the centering changes take place. (It makes no sense to center across a selection that is less than 2 columns wide.) The alignment of all the cells is the row is set back to general, and then a range is defined that is just as wide as you specified, starting at the cell in sStartCell. For this range, the alignment is set to xlCenterAcrossSelection to give the desired results.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (4360) applies to Microsoft Excel 2007, 2010, 2013, and 2016.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Centering a Paragraph with the Keyboard

Need a quick shortcut that you can use to center your paragraph between the margins? The answer is here.

Discover More

Clearing the Undo Stack in a Macro

Excel keeps track of the actions you take so that you can undo those actions if any are taken in error. You may want to ...

Discover More

Using RD Fields with Chapter Headings

The RD field can be handy for pulling together a bunch of documents into a single file. However, using the field can play ...

Discover More

Solve Real Business Problems Master business modeling and analysis techniques with Excel and transform data into bottom-line results. This hands-on, scenario-focused guide shows you how to use the latest Excel tools to integrate data from multiple tables. Check out Microsoft Excel 2013 Data Analysis and Business Modeling today!

More ExcelTips (ribbon)

Changing Cell Colors

If you need to change the color with which a particular cell is filled, the easier method is to use the Fill Color tool, ...

Discover More

Exporting Latitude and Longitude

A handy way to store latitude and longitude values in Excel is to treat them as regular time values. When it comes around ...

Discover More

Formatting for Hundredths of Seconds

When you display a time in a cell, Excel normally displays just the hours, minutes, and seconds. If you want to display ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] (all 7 characters, in the sequence shown) in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 6 - 0?

2020-11-25 11:12:21

Willy Vanhaelen

@Roy
You are right: much to do about nothing? But there is something weird about this tip. The comments don't match with the macro presented here. May be it has been changed? Any how this one is rather clumsy and way to complicated.

Here is my tiny version (almost one quarter in size):

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address <> "$A$1" Then Exit Sub
Dim sStartCell As String
sStartCell = "B1"
Range(sStartCell).EntireRow.HorizontalAlignment = xlGeneral
Range(sStartCell).Resize(1, Target).HorizontalAlignment = xlCenterAcrossSelection
End Sub


2020-11-23 15:20:53

Roy

Actually, there can be a point to spanning a single cell. If coiumns, or cells, are added JUST to its right, then the span will follow to include the appropriate cells to its right.

Esoteric, yes, but potentially of (some) use. Every million years.


2017-10-24 15:48:53

Ron

Allen, in your VBA examples, I think it would be helpful if you added apostrophied comments at the end of the most important lines of code. For me, that would enhance the learning process by making it easier to comprehend what is happening in the subroutine.


2017-09-27 10:45:45

Willy Vanhaelen

@Henk
Indeed there is a little typo in the macro:
Replace
Rows(Range("SPAN").Row).HorizontalAlignment = xlGeneral
with
Rows(Range("BEGIN").Row).HorizontalAlignment = xlGeneral

The error you describe doesn't occur if "span" and "begin" are on the same row but otherwise it does.


2017-09-26 05:05:00

Henk

@Willy
It works fine if you increase the value of "span", but when you decrease it, it basically ignores the change.


2017-09-25 02:37:52

Dave Kerr

@Steve
The macro needs to be saved into the code sheet for the worksheet itself, not the module for the workbook. To access this quickly, simply right-click on the tab for the sheet and select View Code.


2017-09-24 07:24:15

Steve Jones

I copied both versions to a new module in a new workbook, saved the new workbook, enabled macros, but can't get the code to run. What am I missing?


2017-09-23 13:43:30

Willy Vanhaelen

The macro of this tip works fine if your title is in row 1 to 9 but crashes when you want your title in row 10 or any row that ends with a zero (20, 30...). For all other rows it will do nothing if you want to increase the number of columns you want to center across.

Here after is my (tiny) version that works properly. The only difference is that I do not use the sWidth and sStartCell variables. I prefer to define a range name to those cells: "span" for the cell that contains how many columns you want to center across (A1 in this tip's example) and "begin" for the first cell at the left of the range where the centering is to occur (B1 in this tip's example). This has the advantage that if you move the title you don't have to change anything in the macro code, it still works with the title in its new position. My version also removes the "center across" if you delete the span width or enter a 0 or 1 in that cell.

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address <> Range("span").Address Then Exit Sub
Dim i As Integer
Rows(Range("span").Row).HorizontalAlignment = xlGeneral
i = Range("span").Value
Range("begin").Resize(1, i - (i = 0)).HorizontalAlignment = xlCenterAcrossSelection
End Sub


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.