VBA: Declare a cell range as a value for a Constant

KP_SoCal

Board Regular
Joined
Nov 17, 2009
Messages
116
Instead of using a Dim statement in the code listed below, I would like to make this into a Constant and set the value to a specific range. So instead of a the current Dim statement being Dim ocell in Target.Cells, I would have a statement something like Const ocell As String = Range("F2:G16,K2:L16"). Unfortunately I have not been able to get this to work as a Constant. Any ideas what I'm doing wrong? Thanks!


Private Sub Worksheet_Change(ByVal Target As Range)
Dim ocell As Range
For Each ocell In Target.Cells
If Len(ocell.Value) <> Len(Trim(ocell.Value)) Then
ocell.Value = Trim(ocell)
MsgBox "! Leading/trailing spaces are not allowed and have been trimmed from : " & ocell.Address
Else
If Len(Replace(ocell.Value, " ", "")) <> Len(ocell.Value) Then
ocell.Value = Replace(ocell.Value, " ", "")
MsgBox "! Embedded spaces are not allowed and have been trimmed from : " & ocell.Address
End If
End If
Next
End Sub
 
wigi, thanks so much!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

I was toying with this for hours trying to get it to work and the code you provided brings it together beautifully! Also, you bring up a good point. I should be using code tags. I will do this going forward. Thanks again! :biggrin::biggrin::biggrin:
 
Upvote 0

Excel Facts

Can you AutoAverage in Excel?
There is a drop-down next to the AutoSum symbol. Open the drop-down to choose AVERAGE, COUNT, MAX, or MIN

Forum statistics

Threads
1,216,309
Messages
6,130,002
Members
449,552
Latest member
8073662045

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top