5

I am totally new to MS Excel and VBA Macro. I wanna know how to format cells or have an overall control on the spreadsheet using Macro VB. I have here a very simple code just to illustrate what I want to know.

macro_format_test.xlsm:

Private Sub Worksheet_Activate()
    Me.Unprotect
    Me.Cells.ClearContents

    Dim ws As Worksheet
    Set ws = Worksheets("Sheet1")

    ws.Cells(1, 1) = "ID"
    ws.Cells(1, 2) = "Name"
    ws.Cells(1, 3) = "Address"

    Me.Protect
End Sub

In the codes...

ws.Cells(1, 1) = "ID"
ws.Cells(1, 2) = "Name"
ws.Cells(1, 3) = "Address"

I want those to appear bold, italized, and centered. I also want to set he column width using codes. How am I gonna do that??? Please help. You can also give me some references regarding this because everytime I try google all I can see are how to add UserForm which I don't need as of now. Thanks in advance.

2 Answers 2

12
With Range("A1:C1")
    .HorizontalAlignment = xlCenter
    .Font.Italic = True
    .Font.Bold = True
    .EntireColumn.ColumnWidth = 15
End With

By the way, the easiest way to figure out what the macro would be for something like this is to Click the Record Macro button, make your changes manually, and then examine the code that was produced for you. It isn't always the most efficient code, and you usually have to tweak it slightly, but it should give you a basic idea.

2
  • Thanks for you answer. This gives an idea. Sep 23, 2011 at 2:03
  • That Record Macro tip is one of the easiest ways to program that I've heard of.
    – Noumenon
    Feb 16, 2019 at 15:49
3

I presume you want to run this on the sheet this is activated, so your unprotecting of the current sheet looks inconsistent with you then defining Sheet1 as the sheet to work on

But as you did use a sheet variable ws, then you would apply Paul's formatting part as below to be consistent with your code (ie to work on a worksheet stored in ws). Also writing a one shot array to a range is more efficient than a cell by cell write. Not visible in your 3 cell example, but it will be noticeable when writing 1000's of values

Private Sub Worksheet_Activate()
    Me.Unprotect
    Me.Cells.ClearContents
    Dim ws As Worksheet
    Set ws = Worksheets("Sheet1")
    Dim MyArray()
    MyArray = Array("ID", "Name", "Address")
    With ws.Range(ws.[a1], ws.[c1])
        .Value = MyArray
        .HorizontalAlignment = xlCenter
        .Font.Italic = True
        .Font.Bold = True
        .EntireColumn.ColumnWidth = 15
    End With
    Me.Protect
End Sub
1
  • Thanks for this one... Its a big help on my project. Sep 23, 2011 at 3:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.