简体   繁体   English

如何在 VBA 的范围数组中引用单个单元格以对其进行排序?

[英]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.我想要做的是按字母顺序按 A、B、C、D 对它们进行排序,而不会弄乱添加的信息。 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?知道我怎么能 go 关于这个? 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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