简体   繁体   中英

How do I reference a single cell within an array of ranges in VBA to sort by it?

So I have several different components, some of which have different subcomponents listed under them within the same sheet in a different column, like so:

1    C
2    B
           bi            10%
           bii           30%
           biii          60%
3    A
4    D
           di            20%
           dii           80%
etc.

What I want to do is sort them by A, B, C, D alphabetically without it also messing with the added info. Right now I have a code that counts each element, sizes the array appropriately, then loops in each range via selecting all associated rows for each item and looping the range in. However, when I try to sort, I can't seem to get it to work. Any idea how I can go about this? Thanks.


Dim everything() As Range
Dim check As Range
Dim count As Range

Dim lr As Long
Dim x As Long
Dim y As Long
Dim z As Long
Dim q As Long

Dim Temptxt1 As String
Dim Temptxt2 As String

y = 0
z = 0
q = 0
With ThisWorkbook.Sheets("Names and Vendors")
lr = .Cells(.Rows.count, "B").End(xlUp).Row

    'Counts number of elements to size the "everything" array
    For z = 2 To lr
    Set count = .Range("B" & z)
        If IsEmpty(count) = False Then
            q = q + 1
            End If
    Next z
    ReDim everything(z) As Range 'Resizes array

    'Loops all RM info into array by each distinct range
    For x = 2 To lr
        Set check = .Range("B" & x).EntireRow
        If IsEmpty(.Range("B" & 1 + x)) = True Then
            Do While IsEmpty(.Range("B" & 1 + x)) = True And x < lr
                    Set check = Union(check, .Range("B" & 1 + x).EntireRow)
                    x = x + 1
                Loop
        End If
        Set everything(y) = check
        y = y + 1
        Next x

    'This is where the code breaks. It gives me a type mismatch.
    For x = LBound(everything) To UBound(everything)
    For y = x To UBound(everything)
      If UCase(everything(y)) < UCase(everything(x)) Then
        Temptxt1 = everything(x).Range(1, 2)
        Temptxt2 = everything(y).Range(1, 2)
        everything(x) = Temptxt2
        everything(y) = Temptxt1
      End If
     Next y
  Next x
End With
End Sub

Was a little cheeky in how I did this:

Dim sorting As Range
Dim everything() As Range

'Values looped into everything() in different code not pasted here
'y is likewise calculated elsewhere

Set sorting = everything(y)

sorting.Offset(0, 1).Select
ActiveCell.Select

'The two values I need to sort by are below
Temp1 = "" & ActiveCell.Value
ven1 = "" & ActiveCell.Offset(0, 1).Value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM