PDA

View Full Version : Solved: Loop help



excelliot
04-23-2007, 11:48 PM
I dont understand why dototal is working but dototal2 is not??:banghead:


Option Explicit
Sub dototal()
Dim r1 As Range
Dim r2 As Range
Dim cell As Range

Set r1 = Application.InputBox("Select, with the mouse, the range to be re-assigned", Type:=8)
Set r2 = Application.InputBox("Select, with the mouse, the range to be re-assigned", Type:=8)

Range(r1, r2).Select
For Each cell In Selection
If ActiveCell.Value = "" Then
ActiveCell.Value = ActiveCell.Value

Else
ActiveCell.Value = "=" & ActiveCell.Value
End If

ActiveCell.Offset(1, 0).Select

Next

End Sub



Sub dototal2()
Dim r1 As Range
Dim cell As Range

Set r1 = Application.InputBox("Select, with the mouse, the first range to assign", Type:=8)

For Each cell In r1
If ActiveCell.Value = "" Then
ActiveCell.Value = ActiveCell.Value

Else
ActiveCell.Value = "=" & ActiveCell.Value
End If

ActiveCell.Offset(1, 0).Select

Next

End Sub

Haldun
04-24-2007, 12:22 AM
When you change dototal2 sub like following, it is working...

Haldun

Sub dototal2()
Dim r1 As Range
Dim cell As Range
Set r1 = Application.InputBox("Select, with the mouse, the first cell to assign", Type:=8)
For Each cell In r1
If cell.Value <> "" Then
cell.Value = "=" & cell.Value
End If
Next
End Sub


You are using For..Next loop in a selection with cell declaration. so it is unnecessary to use ActiveCell...
Sub dototal()
Dim r1 As Range
Dim r2 As Range
Dim cell As Range
Set r1 = Application.InputBox("Select, with the mouse, the range to be re-assigned", Type:=8)
Set r2 = Application.InputBox("Select, with the mouse, the range to be re-assigned", Type:=8)
For Each cell In Range(r1, r2)
If cell.Value <> "" Then
cell.Value = "=" & cell.Value
End If
Next
End Sub

Bob Phillips
04-24-2007, 12:31 AM
The reason one works and the other does not is because you select the range targetted in the working version. If you do the same in the other, it too will work.

Bob Phillips
04-24-2007, 12:40 AM
BTW, all the selectin is not necessary

Sub dototal2()
Dim r1 As Range
Dim cell As Range

Set r1 = Application.InputBox("Select, with the mouse, the first cell to assign", Type:=8)

For Each cell In r1
If cell.Value "" Then
cell.Value = "=" & cell.Value
End If
Next

End Sub

excelliot
04-24-2007, 01:17 AM
thnks