Sort range without sorting it in a spreadsheet - vba

Question is about sorting data in VBA. Suppose I have a Range("A1:A10") which I want to sort in ascending order. However, I do not want any changes in my spreadsheet (so all the calculations are made within a VBA code). The output of the operation should be a NewRange where all the numbers are sorted.
Has someone ideas about this problem?

Here is a very simple little routine to sort a two-dimensional array such as a range:
Option Base 1
Option Explicit
Function SortThisArray(aryToSort)
Dim i As Long
Dim j As Long
Dim strTemp As String
For i = LBound(aryToSort) To UBound(aryToSort) - 1
For j = i + 1 To UBound(aryToSort)
If aryToSort(i, 1) > aryToSort(j, 1) Then
strTemp = aryToSort(i, 1)
aryToSort(i, 1) = aryToSort(j, 1)
aryToSort(j, 1) = strTemp
End If
Next j
Next i
SortThisArray = aryToSort
End Function
How to use this sort function:
Sub tmpSO()
Dim aryToSort As Variant
aryToSort = Worksheets(1).Range("C3:D9").Value2 ' Input
aryToSort = SortThisArray(aryToSort) ' sort it
Worksheets(1).Range("G3:H9").Value2 = aryToSort ' Output
End Sub
Notes:
The range sorted here is on Worksheet(1) in the Range("C3:D9") and the output is going on the same sheet into Range("G3:H9")
The range will be sorted in ascending order.
The range will be sorted based on the first column (here column C). If you wish to sort for another column then you just have to change all the aryToSort(i, 1) and aryToSort(j, 1) to which ever column you wish to sort. For example by column 2: aryToSort(i, 2) and aryToSort(j, 2).
UPDATE:
If you prefer to use the above as a function then this is also possible like this:
Option Base 1
Option Explicit
Function SortThisArray(rngToSort As range)
Dim i As Long
Dim j As Long
Dim strTemp As String
Dim aryToSort As Variant
aryToSort = rngToSort.Value2
For i = LBound(aryToSort) To UBound(aryToSort) - 1
For j = i + 1 To UBound(aryToSort)
If aryToSort(i, 1) > aryToSort(j, 1) Then
strTemp = aryToSort(i, 1)
aryToSort(i, 1) = aryToSort(j, 1)
aryToSort(j, 1) = strTemp
End If
Next j
Next i
SortThisArray = aryToSort
End Function
And this is how you would use the function:

This is just a sample that you may adapt to your needs, it uses B11:B20 as NewRange:
Sub SortElseWhere()
Dim A As Range, NewRange As Range
Set A = Range("A1:A10")
Set NewRange = Range("B11:B20")
A.Copy NewRange
NewRange.Sort Key1:=NewRange(1, 1), Order1:=xlAscending, Header:=xlNo, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End Sub
The original cells are not sorted, they are merely copied to another location which is sorted.
EDIT#1:
In this version, NewRange is not a range of cells, but an internal array:
Sub SortElseWhere2()
Dim A As Range, NewRange(1 To 10) As Variant
Dim i As Long, strng As String
i = 1
Set A = Range("A1:A10")
For Each aa In A
NewRange(i) = aa
i = i + 1
Next aa
Call aSort(NewRange)
strng = Join(NewRange, " ")
MsgBox strng
End Sub
Public Sub aSort(ByRef InOut)
Dim i As Long, J As Long, Low As Long
Dim Hi As Long, Temp As Variant
Low = LBound(InOut)
Hi = UBound(InOut)
J = (Hi - Low + 1) \ 2
Do While J > 0
For i = Low To Hi - J
If InOut(i) > InOut(i + J) Then
Temp = InOut(i)
InOut(i) = InOut(i + J)
InOut(i + J) = Temp
End If
Next i
For i = Hi - J To Low Step -1
If InOut(i) > InOut(i + J) Then
Temp = InOut(i)
InOut(i) = InOut(i + J)
InOut(i + J) = Temp
End If
Next i
J = J \ 2
Loop
End Sub

Here I am submitting slightly different sort routine.It sorts the 2nd column first then 1st column.
Function BubbleSort(TempArray() As Variant, SortIndex As Long)
Dim blnNoSwaps As Boolean
Dim lngItem As Long
Dim vntTemp(1 To 2) As Variant
Dim lngCol As Long
Do
blnNoSwaps = True
For lngItem = LBound(TempArray) To UBound(TempArray) - 1
If TempArray(lngItem, SortIndex) > TempArray(lngItem + 1, SortIndex) Then
blnNoSwaps = False
For lngCol = 1 To 2
vntTemp(lngCol) = TempArray(lngItem, lngCol)
TempArray(lngItem, lngCol) = TempArray(lngItem + 1, lngCol)
TempArray(lngItem + 1, lngCol) = vntTemp(lngCol)
Next
End If
Next
Loop While Not blnNoSwaps
End Function
Sub Test()
Dim vntData() As Variant
vntData = range("C3:D9")
BubbleSort vntData, 2
BubbleSort vntData, 1
range("G3:H9") = vntData
End Sub
Results obtained from this routine are shown below.

Related

VBA Code for Finding Cells Below which match the key

I have the following requirement I have 2 columns with unique keys called code. In one column below the code, there are one or multiple values present which is the answer. Like in below format
A X
1
2
B Y
9
3
Now the code will have a value populated in next column, while answers wont.
Now I have to find answers for all codes like A, B, C etc. For e.g If I compare with A then answer should be 1,2. I was writing a small subroutine as a beginning but I am facing issues. Can you please correct it
Sub CalculateCellValue()
Dim ValuesBelow As Variant
Dim ValuesRight As String
Dim rows1 As Integer
rows1 = 4
Dim colC As Integer
colC = 2
ValuesRight = ActiveSheet.Cells(rows1 + 1, colC + 1)
While (Not IsEmpty(ValuesRight))
ValuesBelow = ActiveSheet.Cells(rows1 + 1, colC)
rows1 = rows1 + 1
ValuesRight = ActiveSheet.Cells(rows1 + 1, colC + 1)
Wend
MsgBox (ValuesBelow)
End Sub
Purely for an ordered example as shown:
Option Explicit
Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Sheet5") 'Change as appropriate
Dim myArr()
myArr = ws.Range("A1:B" & GetLastRow(ws, 1)).Value
Dim i As Long
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
For i = LBound(myArr, 1) To UBound(myArr, 1)
If myArr(i, 2) <> vbNullString Then
If Not dict.exists(myArr(i, 1)) Then
Dim currKey As String
currKey = myArr(i, 1)
dict.Add myArr(i, 1), vbNullString
End If
Else
dict(currKey) = dict(currKey) & ", " & myArr(i, 1)
End If
Next i
Dim key As Variant
For Each key In dict
MsgBox key & " = " & Right$(dict(key), Len(dict(key)) - 1)
Next key
End Sub
Public Function GetLastRow(ByVal ws As Worksheet, Optional ByVal columnNumber As Long = 1) As Long
With ws
GetLastRow = .Cells(.Rows.Count, columnNumber).End(xlUp).Row
End With
End Function
I used below code to match my requirement
Function findBelowAll(rows1 As Long)
Dim ValuesBelow() As Variant
ReDim ValuesBelow(1 To 1) As Variant
Dim ValuesRight As Variant
Dim colC As Long
colC = 1
Dim i As Long
ValuesRight = ""
While (ValuesRight = "")
rows1 = rows1 + 1
' change / adjust the size of array
ReDim Preserve ValuesBelow(1 To UBound(ValuesBelow) + 1) As Variant
' add value on the end of the array
ValuesBelow(UBound(ValuesBelow)) =
Worksheets(ActiveSheet.Name).Cells(rows1, colC).Value
ValuesRight = Worksheets(ActiveSheet.Name).Cells(rows1, 2).Value
Wend
For i = LBound(ValuesBelow) To UBound(ValuesBelow) - 1
findBelowAll = findBelowAll & ValuesBelow(i) & vbNewLine
Next i
End Function

How can I get the text after the second bracket in VBA?

Trying to get the value after the second bracket, I try to work with this one i created but it's not working properly and getting more complicated while I am having more brackets in each row.. Any idea. I uploaded couple images to understand the input and output.
Sub stringtest()
Dim text As String, i As Long, firstbracket As Long, secondbracket As Long
Dim extractTest As String, y As Long
y = 1
For i = 1 To 10
text = Worksheets("Sheet1").Cells(i, 1).Value
firstbracket = InStr(1, text, "[")
secondbracket = InStr(firstbracket + 1, text, "]")
extractTest = Mid(text, firstbracket + 1, secondbracket)
Worksheets("Sheet1").Cells(y, 2).Value = extractTest
y = y + 1
Next i
End Sub
Try splitting by the second bracket, then using Left() to determine the length of the string
Option Explicit
Public Sub GetStringAfter2ndBracketInSequentialColumns()
Dim i As Long, j As Long, nextRow As Long, ub As Long, lr As Long
Dim extract As Variant, found As Long, nextCol As Long
With Sheet1
lr = .UsedRange.Rows.Count
nextRow = 1
nextCol = 2
For i = 1 To lr
extract = Split(.Cells(i, 1).Value2, "]")
ub = UBound(extract)
If ub > 0 Then
For j = 0 To ub
If Len(extract(j)) > 0 Then
If Left(extract(j), 1) <> "[" Then
found = InStr(1, extract(j), "[")
If found = 0 Then found = Len(extract(j)) + 1
.Cells(nextRow, nextCol).Value2 = Left(extract(j), found - 1)
nextRow = nextRow + 1
If nextRow > lr Then
nextRow = 1
nextCol = nextCol + 1
End If
End If
End If
Next j
End If
Next i
End With
End Sub
Test results:
This is how one of the strings (cell A1) looks like after the split
Edit: measurements for all solutions provided so far:
Timers (with 100,000 rows)
0.824 secs - TextToColumns (0.81054, 0.82812) - Output: same row split to many cols
1.679 secs - Split cells (1.66796, 1.64453) - Output: sequentially by rows, then cols
3.757 secs - ArrayList (3.69140, 3.78125) - Output: sequentially in one column
here's a short and quite fast approach
Sub main()
With Range("A1", Cells(Rows.Count, 1).End(xlUp))
.Replace what:="[*]", replacement:="|", lookat:=xlPart
.TextToColumns DataType:=xlDelimited, Other:=True, OtherChar:="|"
.Columns(1).Delete xlToLeft
End With
End Sub
Here's little different approach using ArrayList
Dim rng As Range
Dim arl As Object
Dim strVal
Dim i As Long
Set arl = CreateObject("System.Collections.ArrayList")
For Each rng In Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)
strVal = Split(Replace(rng.Value, "[", "]"), "]")
For i = 2 To UBound(strVal) Step 2
arl.Add CStr(strVal(i))
Next i
Next rng
For i = 0 To arl.Count - 1
Range("B" & i + 1).Value = arl.Item(i)
Next i
Set arl = Nothing

Excel VBA - Auto FIlter and Advanced filter usage error

I have a requirement where in, I need to use the auto filter to filter the data first and then am using the advanced filter to get the Unique values alone. But the advanced filter doesn't take the auto filtered value alone. How do I use them together?
Here goes my code,
Colmz = WorksheetFunction.Match("RSDate", Sheets("RS_Report").Rows(1), 0)
ActiveSheet.ListObjects("RS").Range.AutoFilter Field:=Colmz, Criteria1:="YES"
ActiveSheet.Range("B1:B65536").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("CSRS").Range("B14"), Unique:=True
Kindly correct me and share your suggestions. Thanks
I would stick the unique values in an array - it's faster and less likely to break -
sub uniquearray()
Colmz = WorksheetFunction.Match("RSDate", Sheets("RS_Report").Rows(1), 0)
ActiveSheet.ListObjects("RS").Range.AutoFilter Field:=Colmz, Criteria1:="YES"
Call creatary(curary, Sheets("RS_Report"), Letter(Sheets("RS_Report"), "RSDate")): Call eliminateDuplicate(curary): Call BuildArrayWithoutBlankstwo(curary): Call Alphabetically_SortArray(curary)
For Each cell In curary
'do what you need to do with the unique array list
Next cell
end sub
Function creatary(ary As Variant, sh As Worksheet, ltr As String)
Dim x, y, rng As Range
ReDim ary(0)
Set rng = sh.Range(ltr & "2:" & ltr & sh.Range("A1000000").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
x = 0
For Each y In rng
If Not Application.IsError(y) Then
If Not IsNumeric(y) Then
ary(x) = y
End If
x = x + 1
ReDim Preserve ary(x)
End If
Next y
End Function
Function BuildArrayWithoutBlankstwo(ary As Variant)
Dim AryFromRange() As Variant, AryNoBlanks() As Variant
Dim Counter As Long, NoBlankSize As Long
'set references and initialize up-front
ReDim AryNoBlanks(0 To 0)
NoBlankSize = 0
'load the range into array
AryFromRange = ary
'loop through the array from the range, adding
'to the no-blank array as we go
For Counter = LBound(AryFromRange) To UBound(AryFromRange)
If ary(Counter) <> 0 Then
NoBlankSize = NoBlankSize + 1
AryNoBlanks(UBound(AryNoBlanks)) = ary(Counter)
ReDim Preserve AryNoBlanks(0 To UBound(AryNoBlanks) + 1)
End If
Next Counter
'remove that pesky empty array field at the end
If UBound(AryNoBlanks) > 0 Then
ReDim Preserve AryNoBlanks(0 To UBound(AryNoBlanks) - 1)
End If
'debug for reference
ary = AryNoBlanks
End Function
Function eliminateDuplicate(ary As Variant) As Variant
Dim aryNoDup(), dupArrIndex, i, dupBool, j
dupArrIndex = -1
For i = LBound(ary) To UBound(ary)
dupBool = False
For j = LBound(ary) To i
If ary(i) = ary(j) And Not i = j Then
dupBool = True
End If
Next j
If dupBool = False Then
dupArrIndex = dupArrIndex + 1
ReDim Preserve aryNoDup(dupArrIndex)
aryNoDup(dupArrIndex) = ary(i)
End If
Next i
ary = aryNoDup
End Function
Function Alphabetically_SortArray(ary)
Dim myArray As Variant
Dim x As Long, y As Long
Dim TempTxt1 As String
Dim TempTxt2 As String
myArray = ary
'Alphabetize Sheet Names in Array List
For x = LBound(myArray) To UBound(myArray)
For y = x To UBound(myArray)
If UCase(myArray(y)) < UCase(myArray(x)) Then
TempTxt1 = myArray(x)
TempTxt2 = myArray(y)
myArray(x) = TempTxt2
myArray(y) = TempTxt1
End If
Next y
Next x
ary = myArray
End Function
Function Letter(oSheet As Worksheet, name As String, Optional num As Integer)
If num = 0 Then num = 1
Letter = Application.Match(name, oSheet.Rows(num), 0)
Letter = Split(Cells(, Letter).Address, "$")(1)
End Function

How can you put words from a list but in a random order? [duplicate]

I have a list of ID numbers 1101-1137 in cells A1-A37. I would like to click a button to randomly select 20 of these, with no repetitions, and display them in a message box.
What I have right now seems to randomly select from the numbers 1-37, not the actual contents of the cells, and I can't figure out how to fix it. For example, if I delete the number 1137 from cell A37, the number 37 can still end up in the message box; if I replace the number 1105 in cell A5 with the letter E, E will not show up in the message box but 5 can.
However, if I change "Const nItemsTotal As Long = 37" to equal some other number, say 31, it will only output numbers from 1-31.
This is what I have:
Private Sub CommandButton1_Click()
Const nItemsToPick As Long = 20
Const nItemsTotal As Long = 37
Dim rngList As Range
Dim idx() As Long
Dim varRandomItems() As Variant
Dim i As Long
Dim j As Long
Dim booIndexIsUnique As Boolean
Set rngList = Range("A1").Resize(nItemsTotal, 1)
ReDim idx(1 To nItemsToPick)
ReDim varRandomItems(1 To nItemsToPick)
For i = 1 To nItemsToPick
Do
booIndexIsUnique = True ' Innocent until proven guilty
idx(i) = Int(nItemsTotal * Rnd + 1)
For j = 1 To i - 1
If idx(i) = idx(j) Then
' It's already there.
booIndexIsUnique = False
Exit For
End If
Next j
If booIndexIsUnique = True Then
strString = strString & vbCrLf & idx(i)
Exit Do
End If
Loop
varRandomItems(i) = rngList.Cells(idx(i), 1)
Next i
Msg = strString
MsgBox Msg
' varRandomItems now contains nItemsToPick unique random
' items from range rngList.
End Sub
I'm sure it's a silly mistake, but I'm lost. Thank you so much for any help.
If you construct a string containing the IDs already found through randomization, you can check for repeats.
Dim i As Long, msg As String, id As String
msg = Chr(9)
For i = 1 To 20
id = 1100 + Int((37 - 1 + 1) * Rnd + 1)
Do Until Not CBool(InStr(1, msg, Chr(9) & id & Chr(9)))
Debug.Print id & msg
id = 1100 + Int((37 - 1 + 1) * Rnd + 1)
Loop
msg = msg & id & Chr(9)
Next i
msg = Mid(Left(msg, Len(msg) - 1), 2)
MsgBox msg
I've added a little to one line in your code... the line is now:
strString = strString & vbCrLf & Cells(idx(i), 1).Value
the full code is:
Private Sub CommandButton1_Click()
Const nItemsToPick As Long = 20
Const nItemsTotal As Long = 37
Dim rngList As Range
Dim idx() As Long
Dim varRandomItems() As Variant
Dim i As Long
Dim j As Long
Dim booIndexIsUnique As Boolean
Set rngList = Range("A1").Resize(nItemsTotal, 1)
ReDim idx(1 To nItemsToPick)
ReDim varRandomItems(1 To nItemsToPick)
For i = 1 To nItemsToPick
Do
booIndexIsUnique = True ' Innocent until proven guilty
idx(i) = Int(nItemsTotal * Rnd + 1)
For j = 1 To i - 1
If idx(i) = idx(j) Then
' It's already there.
booIndexIsUnique = False
Exit For
End If
Next j
If booIndexIsUnique = True Then
strString = strString & vbCrLf & Cells(idx(i), 1).Value
Exit Do
End If
Loop
varRandomItems(i) = rngList.Cells(idx(i), 1)
Next i
Msg = strString
MsgBox Msg
' varRandomItems now contains nItemsToPick unique random
' items from range rngList.
End Sub
So rather than returning the number, it uses the number returned to look at the value on the row that it relates to.
Just shuffle the indices:
Sub MAIN()
Dim ary(1 To 37) As Variant
Dim i As Long, j As Long
For i = 1 To 37
ary(i) = i
Next i
Call Shuffle(ary)
msg = ""
For i = 1 To 20
j = ary(i)
msg = msg & vbCrLf & Cells(j, 1).Value
Next i
MsgBox msg
End Sub
Public Sub Shuffle(InOut() As Variant)
Dim i As Long, j As Long
Dim tempF As Double, Temp As Variant
Hi = UBound(InOut)
Low = LBound(InOut)
ReDim Helper(Low To Hi) As Double
Randomize
For i = Low To Hi
Helper(i) = Rnd
Next i
j = (Hi - Low + 1) \ 2
Do While j > 0
For i = Low To Hi - j
If Helper(i) > Helper(i + j) Then
tempF = Helper(i)
Helper(i) = Helper(i + j)
Helper(i + j) = tempF
Temp = InOut(i)
InOut(i) = InOut(i + j)
InOut(i + j) = Temp
End If
Next i
For i = Hi - j To Low Step -1
If Helper(i) > Helper(i + j) Then
tempF = Helper(i)
Helper(i) = Helper(i + j)
Helper(i + j) = tempF
Temp = InOut(i)
InOut(i) = InOut(i + j)
InOut(i + j) = Temp
End If
Next i
j = j \ 2
Loop
End Sub
another one approach:
Sub test()
Dim Dic As Object, i%
Set Dic = CreateObject("Scripting.Dictionary")
Dic.comparemode = vbTextCompare
While Dic.Count <> 20
i = WorksheetFunction.RandBetween(1, 37)
If Not Dic.exists(i) Then Dic.Add i, Cells(i, "A")
Wend
MsgBox Join(Dic.Items, Chr(13))
End Sub
test:

Sort Combobox VBA

I have been thinking how to sort the values in a combobox.
I add items to the ComboBox when I initilize the form because the number of values are constantly increasing on a sheet.
I use the next code to add the items:
With ComboBox1
lastcell = ThisWorkbook.Sheets("1").Range("F1000000").End(xlUp).Row + 1
For i = 2 To lastcell
.AddItem ThisWorkbook.Sheets("1").Cells(i, 6)
Next i
End With
I thought to copy the values that I am going to add on the ComoBox to another sheet and there sort them in the new sheet, it works fine but it doesn't seem to be a smart option, meaning that I create another sheet and then copy the values and sort them instead of sorting them directly.
My question is, anyone knows how to do it directly from the original sheet? I dont know anything of API so, please, only VBA code. I alredy check on MSDN but I can't figure out how to make it work.
Thanks and if more info is needed, please, let me know it.
PS: I cant sort them directly from the original sheet because this Sheet has to be with a static order
You can read the values from the sheet into an array, sort this with code and then add the items.
This code will do this, using a Quicksort:
Private Sub UserForm_Initialize()
Dim varRange() As Variant
Dim lngLastRow As Long
Dim i As Long
lngLastRow = Range("F:F").Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
varRange = Range("F:F").Resize(lngLastRow).Cells
subQuickSort varRange
Me.ComboBox1.List = varRange
End Sub
Public Sub subQuickSort(var1 As Variant, _
Optional ByVal lngLowStart As Long = -1, _
Optional ByVal lngHighStart As Long = -1)
Dim varPivot As Variant
Dim lngLow As Long
Dim lngHigh As Long
lngLowStart = IIf(lngLowStart = -1, LBound(var1), lngLowStart)
lngHighStart = IIf(lngHighStart = -1, UBound(var1), lngHighStart)
lngLow = lngLowStart
lngHigh = lngHighStart
varPivot = var1((lngLowStart + lngHighStart) \ 2, 1)
While (lngLow <= lngHigh)
While (var1(lngLow, 1) < varPivot And lngLow < lngHighStart)
lngLow = lngLow + 1
Wend
While (varPivot < var1(lngHigh, 1) And lngHigh > lngLowStart)
lngHigh = lngHigh - 1
Wend
If (lngLow <= lngHigh) Then
subSwap var1, lngLow, lngHigh
lngLow = lngLow + 1
lngHigh = lngHigh - 1
End If
Wend
If (lngLowStart < lngHigh) Then
subQuickSort var1, lngLowStart, lngHigh
End If
If (lngLow < lngHighStart) Then
subQuickSort var1, lngLow, lngHighStart
End If
End Sub
Private Sub subSwap(var As Variant, lngItem1 As Long, lngItem2 As Long)
Dim varTemp As Variant
varTemp = var(lngItem1, 1)
var(lngItem1, 1) = var(lngItem2, 1)
var(lngItem2, 1) = varTemp
End Sub
It depends on circumstances, type and structure of data. But i prefer to do it this way:
You could alternatively use an array and a bubble sort algo :)
modify the code a little bit to suit your case
Option Explicit
Sub WITH_COMBOBOX()
Dim i As Long
Dim arr() As String
Dim lastCell As Long
lastCell = 500
ReDim arr(lastCell)
Call FillAndSortArray(arr)
For i = 2 To lastCell
.AddItem arr(i - 2)
Next i
End Sub
Sub FillAndSortArray(ByRef myArray() As String)
Dim i As Long
For i = LBound(myArray) To UBound(myArray)
myArray(i) = CStr(ThisWorkbook.Sheets(1).Range("F" & i + 2).Value)
Next i
Call BubbleSort(myArray)
End Sub
Sub BubbleSort(ByRef myArray() As String)
Dim i As Long, j As Long
Dim Temp As String
For i = LBound(myArray) To UBound(myArray) - 1
For j = i + 1 To UBound(myArray) - 1
If myArray(i) > myArray(j) Then
Temp = myArray(j)
myArray(j) = myArray(i)
myArray(i) = Temp
End If
Next j
Next i
End Sub
Try below code :
Sub GetAction()
Dim rng As Range, lastcell As Long
lastcell = Range("F1000").End(xlUp).Row + 1
Set rng = Range("F1:F" & lastcell) ' assuming to start from F1
If Not rng Is Nothing Then
rng.Sort Range("F1")
ComboBox1.ListFillRange = rng.Address
End If
End Sub
for sorting 123 for number
For Each cell In ThisWorkbook.Sheets("sheet1").Range("list1")
Me.ComboBox1.AddItem cell
Next cell
With Me.ComboBox1
For x = LBound(.list) To UBound(.list)
For y = x To UBound(.list)
If .list(y, 0) + 0 < .list(x, 0) + 0 Then
blah = .list(y, 0)
.list(y, 0) = .list(x, 0)
.list(x, 0) = blah
End If
Next y
Next x
End With
for sorting text abcd
For Each cell In ThisWorkbook.Sheets("sheet1").Range("list1")
Me.ComboBox1.AddItem cell
Next cell
With Me.ComboBox1
For x = LBound(.list) To UBound(.list)
For y = x To UBound(.list)
If .list(y, 0) < .list(x, 0) Then
blah = .list(y, 0)
.list(y, 0) = .list(x, 0)
.list(x, 0) = blah
End If
Next y
Next x
End With