1

I have this problem: my code is executed correctly only if 1 cell is selected, it doesn't work with multiple cells selection. What should be changed? Please help.

current code:

Sub adddate()
Dim cell As Range
Dim r As Range
Set r = Selection

For Each cell In Selection
If IsDate(r.Value) Then
Selection.Cells = DateAdd("d", 28, CDate(r))
End If
Next cell

End Sub
Pawel
  • 417
  • 1
  • 6
  • 25
  • See [How to avoid using Select in Excel VBA macros](http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros/28700020#28700020). –  Aug 10 '16 at 09:19

1 Answers1

0

You are setting selection in r and then using it. cell variable never comes in play.

Sub adddate()
Dim cell As Range
Dim r As Range
Set r = Selection

For Each cell In Selection.Celss
If IsDate(cell.Value2) Then 'r = selection, multiple cells can't be evaluated in IsDate, cell is just one single. cell
Selection.Cells = DateAdd("d", 28, CDate(r))
End If
Next cell

End Sub
cyboashu
  • 10,196
  • 2
  • 27
  • 46
  • what do you mean? didn't get you. replace `IsDate(r)` with `IsDate(cell)`, see the answer's code. Also one edit, for dates, use `value2` instead of `value` – cyboashu Aug 10 '16 at 09:18
  • Right, I got it now :) Thanks cyboashu. There is one more issue though: when I select multiple cells and there is value that is not date within selection, whe I run macro this non-date vlue gets converted into date. How do I fix that? – Pawel Aug 10 '16 at 09:23
  • one more issue, means start another question, one thing at a time.:) – cyboashu Aug 10 '16 at 09:24
  • Sure thing. Thanks:) – Pawel Aug 10 '16 at 09:27