• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

How to write function to select worksheets from workbook and change font

ThrottleWorks

Excel Ninja
Hi,

First my apologies for asking this question. I am trying to learn VBA function.
I want to apply formatting changes to n number of worksheets in a workbook.

I have written a simple code to do it. However I am trying to do it by function.
However, I am not able to understand how to do it.

Can anyone please help me in this, will use help function as reference for future learning. Thanks.

I am using below mentioned normal code as of now. How to achieve this by using function.

Code:
'+Assign font, wrap text

    ESRP_Sht.Select
    ESRP_Sht.Cells.Font.Size = 10
    ESRP_Sht.Cells.WrapText = False
    Range("A1").Select

    Laser_Before_Sht.Select
    Laser_Before_Sht.Cells.Font.Size = 10
    Laser_Before_Sht.Cells.WrapText = False
    Range("A1").Select

    P_I_Check_Sht.Select
    P_I_Check_Sht.Cells.Font.Size = 10
    P_I_Check_Sht.Cells.WrapText = False
    Range("A1").Select

    Note_Rate_Check_Sht.Select
    Note_Rate_Check_Sht.Cells.Font.Size = 10
    Note_Rate_Check_Sht.Cells.WrapText = False
    Range("A1").Select

    Workbook_Sht.Select
    Workbook_Sht.Cells.Font.Size = 10
    Workbook_Sht.Cells.WrapText = False
    Range("A1").Select

    Sold_Sht.Select
    Sold_Sht.Cells.Font.Size = 10
    Sold_Sht.Cells.WrapText = False
    Range("A1").Select
    '=Assign font, wrap text
 
As has been explained by others function will return something and you are not expecting a result to be returned.

I think you have got the correct idea from programming viewpoint. It can be implemented like below.

In below example, ApplyShtFmtGen is where you write a general function like code to do repetitive and common tasks for multiple objects. Function Demo
gives call.

Code:
Public Sub Demo()
Dim ESRP_Sht As Worksheet
Dim Laser_Before_sht As Worksheet

Set ESRP_Sht = ThisWorkbook.Sheets(1)
Call ApplyShtFmtGen(ESRP_Sht, 10, False) '\\ Pass arguments for ESRP_Sht

Set Laser_Before_sht = ThisWorkbook.Sheets(2)
Call ApplyShtFmtGen(Laser_Before_sht, 11, False) '\\ Pass arguments for Laser_Before_sht
End Sub


Public Sub ApplyShtFmtGen(wks As Worksheet, lngFontSize As Long, blWrapText As Boolean)
With wks.Cells
    .Font.Size = lngFontSize
    .WrapText = blWrapText
End With
End Sub
 
Last edited:
Back
Top