A Little More Advanced Range Fill-In

  • Thread starter Thread starter Derek Hart
  • Start date Start date
D

Derek Hart

I have this function:

myKey = Key()
Selection.Value = myKey

If the user highlights a range, a specific value is filled into every single
cell highlighted. I want to do this a little better. If the user
highlights several rows and columns, I want the myKey to only fill in if the
column header (Row 1 value) is "Key" - is this possible in VBA?
 
Sub test()

myKey = Key()
For Each cell In ActiveSheet.Selection
If Cells(1, cell.Column) = "Key" Then
cell.Value = myKey
End If
Next cell

End Sub
 
I get the error:

"Compile Error: For Each control variable must be Variant or Object"

How would I correct this code?

Derek
 
did you have the error before my changes? I don't get the error with Excel
2003. Can you post your entire code?
 
Dim myKey As String
myKey = Key()
For Each objCell In ActiveSheet.Selection
If Cells(1, objCell.Column) = "Key" Then
objCell.Value = myKey
End If
Next objCell

What do you think?
 
chaging the variable cell to objcell doesn't solve your problem. there is
something else wrong. I need to see the entire code.
 
I switched ActiveSheet.Selection to just Selection and it solved it. Not
sure why the ActiveSheet reference does not work for me, but it works. Do
you know why I cannot reference ActiveSheet?
 
No idea. I sometimes have problems when more than one workbook is opened.
Sometimes I need to activate the workbook before I select the cell.
Otherwise I don't know.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top