View Single Post
  #1   Report Post  
Posted to microsoft.public.excel.programming
Sharon Sharon is offline
external usenet poster
 
Posts: 183
Default Declaring Objects

I hope this post makes sense. I am trying to learn VB on my own and I know
that I need to declare my objects and know that I would prefer to declare
them early in the code.

I want to write a macro that does a find and replace for "Green", "Yellow",
"Red", and "No" on Sheet1 and replaces the words with the values 1, 2, 3, 4,
respectively. The range of my data is from B1:Q400 and S1:AI400. I named
the non-contiguous range "Colors". I would like to use the name of my range
in my code.

Below is my first attempt to writing a macro, partially using the macro
recorder. The code the recorder gave me was:

Sub FindAndReplace()

Selection.Replace What:="green", Replacement:="1", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
Selection.Replace What:="yellow", Replacement:="2", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
Selection.Replace What:="red", Replacement:="3", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
Selection.Replace What:="no", Replacement:="4", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False

End Sub

Since I don't want the user to have to select the range each time to run the
macro, I want to change the code to apply to the range I named "Colors". So
here's my first attempt at declaring my "Colors" range as my object. Except,
since I don't really know what I'm doing, it doesn't work.

Can anyone help me declare my range "Colors"?

Sub FindAndReplace()

Dim Colors As Range
Set Colors = Colors.Range("B1:Q400", "S1:AI400")

Colors.Replace What:="green", Replacement:="1", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
Colors.Replace What:="yellow", Replacement:="2", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
Colors.Replace What:="red", Replacement:="3", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
Colors.Replace What:="no", Replacement:="4", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
End Sub

Thanks so much,

Sharon