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.
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.
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.