RWayneH
asked on
Writing a If loop
To show how bad I am at writing loops here is something I wrote. I almost wish I was never shown the GoTo command.
I know that there is a different way to write this, like maybe a Do Unitl??
How would I rewrite this with less lines and not having to use the Goto commands?
I know that there is a different way to write this, like maybe a Do Unitl??
How would I rewrite this with less lines and not having to use the Goto commands?
Range("BB2").Select
400
If ActiveCell = "" Then
ActiveCell = SalesOrderNum
GoTo 500
End If
If Not ActiveCell = "" Then
ActiveCell.Offset(1, 0).Select
GoTo 400
'MsgBox ("it is NOT blank ")
End If
500
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
An If block can have an Else clause. And a Do loop can have an Exit Do statement. The combination allows you to avoid needing line numbers.
Sub test3()
Dim SalesOrderNum As Variant
Range("BB2").Select
Do
If ActiveCell.Value = "" Then
ActiveCell.Value = SalesOrderNum
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
End Sub
Alternatively, you can use the .End method to go straight to the bottom of your data:
Sub test2()
Dim SalesOrderNum As Variant
Range("BB3").Select
If Range("BB3").Value <> "" Then Range("BB2").End(xlDown).Offset(1, 0).Select
ActiveCell.Value = SalesOrderNum
End Sub
Can you explain what you are trying to actually do with your code? It appears you're setting the SalesOrderNum variable to blank.
If you really want to set the SalesOrderNum to the last value in column BB, then this code is significantly simpler:
This moves up "from the bottom" in case there are blank cells in column BB.
Regards,
-Glenn
If you really want to set the SalesOrderNum to the last value in column BB, then this code is significantly simpler:
Sub Set_SON()
Dim SalesOrderNum as String
SalesOrderNum = Range("BB" & Cells.SpecialCells(xlLastCell).Row).End(xlUp).Value
End Sub
This moves up "from the bottom" in case there are blank cells in column BB.
Regards,
-Glenn
ASKER
Thanks for the help.
introw = 2
Do until cells(introw,54)=""
introw=introw+1
Loop
cells(introw,54)=SalesOrde