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



所以我有几个不同的组件,其中一些组件在不同的列的同一工作表中列出了不同的子组件,如下所示:

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

我想做的是按字母顺序按 A、B、C、D 对它们进行排序,而不会弄乱添加的信息。现在我有一个代码来计算每个元素,适当地调整数组的大小,然后通过为每个项目选择所有关联的行并循环范围在每个范围内循环。但是,当我尝试排序时,我似乎无法让它工作。知道我该怎么做吗?谢谢。


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

我这样做的方式有点厚颜无耻:

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

最新更新