Вы находитесь на странице: 1из 9

Introduction

One of the basic principles of making VBA Macros is being able to move around your spreadsheets and
either making changes to them or collecting the data that is stored in those cells. There may also be times
where you need to be able to easily propagate a formula that Excel struggles with.

In some cases the effort it takes to make those changes manually is very minimal and using a macro is
not required. But you may just as easily find that the changes you wish to make, or data you need to
collect would take far to long to do by any other means.

In this article, we will show you how to use VBA code to move around a spreadsheet to collect data which
will be stored in variables and how to change cell data to either a static or variable value. We will also
discuss changing various aspects of the cell format such as data type, background color, font color, bold,
italics, underlining, and borders.

Applicable Excel Versions

2003
2007

Outline

I use an outline format for the sake of making future additions and editing easier to include. Below is the
list of items that will be covered:

Cell Navigation
1. Selecting a specific cell A. Using Variables 2. Selecting cell ranges 3.
Selecting cells in relation

Cell Formatting
1. Changing data type 2. Changing background color 3. Changing font color 4.
Bold, Italics, and Underline 5. Borders 6. Alignment

Explanations and Examples

Selecting a specific cell

There are two different methods of selecting a specific cell. You can either use is Column/Row reference,
or you can use the cell's name if you have assigned it one. Here are some examples of each:

Range("A1").Select 'Selects the cell in Column A, Row 1


Range("B4").Select 'Selects the cell in Column B, Row 4
Range("CustName").Select 'Selects the cell labeled "CustName"
Range("OrderNum").Select 'Selects the cell labeled "OrderNum"
A. Using Variables

The first thing you always want to do when you are using variables, is to declare those variables. You
create variables in VBA the same what you do in Visual Basic by giving it a name and selecting a data
type, as seen here:

Dim intCredit as Integer 'Creates an integer variable: intCredit


Dim strCustomer as String 'Creates a string variable: strCustomer

Once you have your variables declared, then you can begin using them. The variables can either be used
to store data from the cell, input data into the cell, or for looping purposes such as a For Loop. Here are
some examples of how to use variables in a macro:

Dim intCredit as Integer Dim strCustomer as String


intCredit = 0 'Assigns the value (0) to intCredit
Range("B1").Select 'B1 contains the Customer Name
strCustomer = ActiveCell.Value 'Assigns the value of the Customer Name
Range("CreditLimit").Select 'Selects a cell labeled "CreditLimit"
ActiveCell.Value = intCredit 'Puts value of intCredit into the cell

So in the above example, the first thing that happens is we declare our two variables (intCredit,
strCustomer). We then assign a static value (0) to the intCredit variable. Then we select the B1 cell and
assign its value to the strCustomer variable. Next, we select the cell that we have labeled as "CreditLimit"
and then assign the value of our intCredit variable to the value of that cell.

Selecting cell ranges

Selecting a cell range is almost exactly the same as selecting a single cell. The only difference is that you
use a colon to separate the beginning and ending cell references, like so:

Range("A1:B4").Select 'Selects cells A1, A2, A3, A4, B1, B2, B3, and B4.
Range("A:A").Select 'Selects the entire Column A
Range("A:C").Select 'Selects Columns A, B, and C
Range("1:1").Select 'Selects all of Row 1
Range("1:57").Select 'Selects Rows 1 through 57

Some examples of why you would want to select a range while using a macro include: changing
background color for column titles, deleting the values within the range, editing font types or colors, or
setting a border and its related properties.

Selecting cells in relation

Selecting cells in relation to one another can be done in a couple of ways. The most effective, in my
experience, is to use the ActiveCell.Offset(Rows,Columns).Select method. Here are a couple of examples
for relational movement:

ActiveCell.Offset(1,0).Select 'Selects cell in same Column, 1 Row DOWN


ActiveCell.Offset(-1,0).Select 'Selects cell in same Column, 1 Row UP
ActiveCell.Offset(0,2).Select 'Selects cell in same Row, 2 Columns RIGHT
ActiveCell.Offset(0,-2).Select 'Selects cell in same Row, 2 Columns LEFT
Cell Formatting

Changing data format

Data format can either be fairly unimportant, or extremely critical. In some cases, such as spreadsheets
that hold data that was exported from a database, you stand a chance of accidentally changing or losing
data if you have the wrong data format selected.

In order to change data format you need to select your cell, or range of cells, that you want to format, and
then set the format on those cells like this:

There is a distinction between changing data format and changing the data type. These are examples of
how to change the format of the data. However, they do not change the data type.

Range("A1").Select 'Selects cell A1 Selection.NumberFormat = "@" 'Sets the


data format to Text
Range("B5:B12").Select 'Selects cells from B5 to B12 Selection.NumberFormat =
"0" 'Sets data format to Number with no decimals
Range("B5:B12").Select 'Selects cells from B5 to B12 Selection.NumberFormat =
"0.00" 'Sets data format to Number with 2 decimals
Range("PurchaseDate").Select 'Selects cell labeled "PurchaseDate"
Selection.NumberFormat = "mm/dd/yy;@" 'Sets data format to Date (ex. 04/25/08)
Range("ItemPrice").Select 'Selects cell labeled "ItemPrice"
Selection.NumberFormat = "$#,##0.00" 'Sets data format to Currency

Changing background color

Changing background colors is another task that is fairly easy to accomplish. This is another command
that can be done either to a single cell, or to a range of cells, and is done like this:

Range("A1").Select With Selection.Interior .Pattern = xlSolid


.PatternColorIndex = xlAutomatic .Color = vbYellow .TintAndShade = 0
.PatternTintAndShade = 0 End With

In the first example there we set the background color of a single cell to Yellow. You can change
"vbYellow" to "vb(color)" to change colors. You can also use color codes in place of the "vbYellow" or
other colors if you wish.
Changing font color

Changing the font color is actually easier than changing background colors, and it too can be used on
either a single cell or a range of cells at once:

Range("A3:A4").Select With Selection.Font .Color = vbRed .TintAndShade = 0 End


With

The second example sets the font color of a range of cells (A3 and A4) to Red. And as with the
background colors, you can use any of the other default VB Colors or color codes in place of the vbRed in
the example.

Bold, Italics, and Underline

Another very easy change that can be made to a single cell or range of cells is to style the font as bold,
italicized, underlined, or any combination of the three. Each of the changes requires its own line of code,
but it takes only one line of code for each one. Here are a few examples:

Bold:

Range("A2").Select Selection.Font.Bold = True

Italics:

Range("A2").Select Selection.Font.Italic = True

Underline:

Range("A1").Select Selection.Font.Underline = xlUnderlineStyleSingle

Bold and Italics:

Range("A4:G4").Select Selection.Font.Italic = True Selection.Font.Bold = True

Bold, Italics, and Underlined:

Range("A2:F3").Select Selection.Font.Bold = True Selection.Font.Italic = True


Selection.Font.Underline = xlUnderlineStyleSingle
Borders

While easy to do, borders do take up quite a few more lines of code than our other examples here, but the
code required is not complex. You can set up a vary large variety of borders, but I will only give examples
of a couple in order to cut down on the space required. Borders are another example of code that can be
used on a single cell or a range of cells:

Set a Thick border around the outside edge of the selected cell(s):

Range("A1:G2").Select With Selection.Borders(xlEdgeLeft) .LineStyle =


xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlMedium 'Use xlThin
for smaller border End With With Selection.Borders(xlEdgeTop) .LineStyle =
xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlMedium 'Use xlThin
for smaller border End With With Selection.Borders(xlEdgeBottom) .LineStyle =
xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlMedium 'Use xlThin
for smaller border End With With Selection.Borders(xlEdgeRight) .LineStyle =
xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlMedium 'Use xlThin
for smaller border End With

Set a Thin border around all cells, including those in the middle of a range:

Range("A4:G5").Select With Selection.Borders(xlEdgeLeft) .LineStyle =


xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With
Selection.Borders(xlEdgeTop) .LineStyle = xlContinuous .ColorIndex = 0
.TintAndShade = 0 .Weight = xlThin End With With
Selection.Borders(xlEdgeBottom) .LineStyle = xlContinuous .ColorIndex = 0
.TintAndShade = 0 .Weight = xlThin End With With
Selection.Borders(xlEdgeRight) .LineStyle = xlContinuous .ColorIndex = 0
.TintAndShade = 0 .Weight = xlThin End With With
Selection.Borders(xlInsideVertical) .LineStyle = xlContinuous .ColorIndex =
0 .TintAndShade = 0 .Weight = xlThin End With With
Selection.Borders(xlInsideHorizontal) .LineStyle = xlContinuous .ColorIndex =
0 .TintAndShade = 0 .Weight = xlThin End With

Take note of the differences between the two examples. In the first one with have four "With Selection..."
statements, while the second example has six. The reason for this is that the first example will only put a
thick border around the outer-most edge of your selected cell or cells. The second example will put a thin
border around all edges of all of your selected cells. If you run both of the examples in a file, you will be
able to see the difference.
Alignment

Another easy change to make to a cell, or range of cells, is the alignment property of the value stored in
those cells. Here are some examples of the different changes you can make to alignment:

Aligned Center (Horizontal):

Range("C15:C18").Select With Selection .HorizontalAlignment = xlCenter End


With

Aligned Right (Horizontal):

Range("D15:D18").Select With Selection .HorizontalAlignment = xlRight End With

Aligned Left (Horizontal):

Range("E15:E18").Select With Selection .HorizontalAlignment = xlLeft End With

Aligned Center (Vertical):

Range("D15:D18").Select With Selection .VerticalAlignment = xlCenter End With

Aligned Top (Vertical):

Range("C15:C18").Select With Selection .VerticalAlignment = xlTop End With

Aligned Center (both Horizontal and Vertical):

Range("F15:F18").Select With Selection .HorizontalAlignment = xlCenter


.VerticalAlignment = xlCenter End With

You can mix and match alignments as need for horizontal and vertical, and there are other alignment
options besides those that I have listed.

Code: Cell Navigation and Formatting Module

Open up a workbook that has three spreadsheets in it labeled "Sheet1", "Sheet2", and "Sheet3"
respectively. Then paste this code into a module, save it, and then run it. You will be able to see an a
working example of all of the items mentioned above.

Code for Cell Navigation and Formatting


Sub NavAndFormatCells()
'The first thing we do is declare our variables
Dim strCustName As String
Dim curCredit As Currency
Dim strStatus As String
'Now we insert our customer information labels
Range("A1").Select
ActiveCell.FormulaR1C1 = "Customer Name"
Range("A2").Select
ActiveCell.FormulaR1C1 = "Customer Status"
Range("A3").Select
ActiveCell.FormulaR1C1 = "Credit Limit"
'Next we set input our customer information
strCustName = "Jason Griffith"
Range("B1").Select
ActiveCell.FormulaR1C1 = strCustName
If strCustName = "Jason Griffith" Then
curCredit = 10000
Else
curCredit = 0
End If
Range("B3").Select
ActiveCell.FormulaR1C1 = curCredit
If curCredit = 0 Then
strStatus = "Poor"
Else
strStatus = "Great"
End If
Range("B2").Select
ActiveCell.FormulaR1C1 = strStatus
'Then we insert our Table lables
Range("A5").Select
ActiveCell.FormulaR1C1 = "Order Number"
Range("B5").Select
ActiveCell.FormulaR1C1 = "Order Date"
Range("C5").Select
ActiveCell.FormulaR1C1 = "Ship Date"
Range("D5").Select
ActiveCell.FormulaR1C1 = "Order Amount"
'Then we simulate a table by using borders
Range("A5:D13").Select
'We set a Thick border around the outside edge, with a Thin
'border around all of the individual cells within the range
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
'We then set a Thick border around our Table Labels
Range("A5,B5,C5,D5").Select
Range("D5").Activate
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
'We then change the background color of our Table Labels
'to vbBlue, and the font color to vbYellow
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = vbBlue
.TintAndShade = 0
.PatternTintAndShade = 0
End With
With Selection.Font
.Color = vbYellow
.TintAndShade = 0
End With
'Now I format cell fonts and colors
Range("B2").Select
If ActiveCell.Value = "Poor" Then
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = vbYellow
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Selection.Font.Bold = False
Selection.Font.Italic = True
Else
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = vbGreen
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Selection.Font.Bold = True
Selection.Font.Italic = False
End If
'Here I change alignment and data types in the table
Range("A5:C13").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
End With
Selection.NumberFormat = "@"
Range("D5:D13").Select
With Selection
.HorizontalAlignment = xlRight
.VerticalAlignment = xlBottom
End With
Selection.NumberFormat = "$#,##0.00"
Range("A5:D5").Select
Selection.Font.Bold = True
Range("A1:A3").Select
Selection.Font.Bold = True
End Sub

Вам также может понравиться