18.11.2014 Views

Microsoft Office

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Part VI<br />

Programming Excel with VBA<br />

The next step is to add the code to handle the Click event for the OKButton control. Follow these steps:<br />

1. Select OKButton from the drop-down list at the top of the module. The VB Editor begins a<br />

new procedure called OKButton_Click.<br />

2. Enter the following code. (The first and last statements have already been entered for you by the<br />

VB Editor.)<br />

Private Sub OKButton_Click()<br />

Application.ScreenUpdating = False<br />

‘ Exit if a range is not selected<br />

If TypeName(Selection) “Range” Then Exit Sub<br />

‘ Upper case<br />

If OptionUpper Then<br />

For Each cell In Selection<br />

If Not cell.HasFormula Then<br />

cell.Value = StrConv(cell.Value, vbUpperCase)<br />

End If<br />

Next cell<br />

End If<br />

‘ Lower case<br />

If OptionLower Then<br />

For Each cell In Selection<br />

If Not cell.HasFormula Then<br />

cell.Value = StrConv(cell.Value, vbLowerCase)<br />

End If<br />

Next cell<br />

End If<br />

‘ Proper case<br />

If OptionProper Then<br />

For Each cell In Selection<br />

If Not cell.HasFormula Then<br />

cell.Value = StrConv(cell.Value, bProperCase)<br />

End If<br />

Next cell<br />

End If<br />

Unload UserForm1<br />

End Sub<br />

The macro starts by turning off screen updating, which makes the macro run a bit faster. Next, the code<br />

checks the type of the selection. If a range is not selected, the procedure ends. The remainder of the procedure<br />

consists of three separate blocks. Only one block is executed, determined by which OptionButton is<br />

selected. The selected OptionButton has a value of True. Finally, the UserForm is unloaded (dismissed).<br />

Testing the UserForm<br />

To try out the UserForm from Excel, follow these steps:<br />

1. Activate Excel.<br />

2. Enter some text into some cells.<br />

3. Select the range with the text.<br />

4. Choose Developer ➪ Code ➪ Macros (or press Alt+F8).<br />

730

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!