Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format excel spreadsheet cells using Excel Macro Module?

Tags:

excel

vba

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.

like image 777
Hopeless Imbecile Avatar asked Sep 23 '11 01:09

Hopeless Imbecile


1 Answers

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.

like image 196
PaulStock Avatar answered Oct 12 '22 22:10

PaulStock