Forum Discussion

arajagopal4's avatar
arajagopal4
Copper Contributor
Feb 02, 2023
Solved

Set range in VBA as the last non blank cell

I am trying to make my VBA code more flexible. I am trying to create a combination of all cells for a column set

 

Columns A through E are the input and Columns H and J show all combinations of the input. To achieve this I wrote a simple macro shown below. However I run into one issue- When selecting the range of each column to create the combination (code lines highlighted below in red) I am specifying the range of cells. So if Aisle entries (column B) goes from 2 entries to 4 entries and I would like to update the combinations to account for this change to generate the new set of combinations, I have to go into the VBA code to change the range to:

 

Set AISLE = Range("B2:B5")

 

Instead of having to do this manually every time is there a way for me to automate the range selection to cell B2 to the last non blank cell- In my case the data will be properly ordered, so no blank cells between entries.

 

Thanks for the help!

 

Here is my code so far


Sub ListAllCombinations()

Dim PICK_ZONE, AISLE, BAY, LEVEL, POSITION As Range
Dim DISP_LOCN, LOCN_BRCD As Range
Dim xStr As String
Dim xFN1, xFN2, xFN3, xFN4, xFN5 As Integer
Dim xSV1, xSV2, xSV3, xSV4, xSV5 As String
Set PICK_ZONE = Range("A2:A2") 'EDIT PICK ZONE DATA RANGE
Set AISLE = Range("B2:B3") 'EDIT AISLE ZONE DATA RANGE
Set BAY = Range("C2:C2") 'EDIT BAY DATA RANGE
Set LEVEL = Range("D2:D2") 'EDIT LEVEL DATA RANGE
Set POSITION = Range("E2:E2") 'EDIT POSITION DATA RANGE
xStr = "-" 'Separator
Set DISP_LOCN = Range("I2") 'Output cell where Pick Tower Display Locations are to be populated
Set LOCN_BRCD = Range("H2") 'Output cell where Pick Tower LOCATION BARCODES are to be populated
For xFN1 = 1 To PICK_ZONE.Count
xSV1 = PICK_ZONE.Item(xFN1).Text
For xFN2 = 1 To AISLE.Count
xSV2 = AISLE.Item(xFN2).Text
For xFN3 = 1 To BAY.Count
xSV3 = BAY.Item(xFN3).Text
For xFN4 = 1 To LEVEL.Count
xSV4 = LEVEL.Item(xFN4).Text
For xFN5 = 1 To POSITION.Count
xSV5 = POSITION.Item(xFN5).Text
DISP_LOCN.Value = xSV1 & xStr & xSV2 & xStr & xSV3 & xStr & xSV4 & xSV5
Set DISP_LOCN = DISP_LOCN.Offset(1, 0)
LOCN_BRCD.Value = xSV1 & xSV2 & xSV3 & xSV4 & xSV5
Set LOCN_BRCD = LOCN_BRCD.Offset(1, 0)
Next
Next
Next
Next
Next

ActiveWorkbook.RefreshAll

End Sub

Resources