【发布时间】:2016-09-22 00:16:03
【问题描述】:
假设我在 excel 中有一个两列数组,其中第一列是文本,第二列是数字。我想要一个命令,该命令将返回根据第二列中的值排序的数组。我不想使用自定义排序命令,因为我希望能够更新第二列中的数值并自动更新排序后的数组。
【问题讨论】:
-
为什么投反对票,什么代码?它只有两列,一列是文本,一列是数字。
假设我在 excel 中有一个两列数组,其中第一列是文本,第二列是数字。我想要一个命令,该命令将返回根据第二列中的值排序的数组。我不想使用自定义排序命令,因为我希望能够更新第二列中的数值并自动更新排序后的数组。
【问题讨论】:
自动排序的唯一其他方法是通过编程...宏。
您可以创建一个按钮并将宏分配给该按钮 要么 您将其置于每次单元格更改时运行宏的选择更改事件中。
由你决定。
在下面的代码中,我是为一个按钮做的:
Sub btnSort()
Dim swapped As Boolean ' Boolean value to check if the values have been swapped
Dim boolEmpty As Boolean ' Boolean value to check if the cell value is empty
Dim tmp1, tmp2 As Variant ' Temporary variable,which holds temporary value
Dim numRows As Integer ' Number of NON-EMPTY rows
Dim tempArray1 As Variant ' Holds values in column 1 with certain values
Dim tempArray2 As Variant ' Holds values in column 2 with numerica values
boolEmpty = False 'Give initial value to variable; Assuming that the first checked cell is NOT EMPTY
'Count the number of cells with actual values in them
numRows = 0
ctr = 1
Do While (boolEmpty <> True)
'If the cell value contains something then increment variable numRows
If Sheet6.Cells(ctr, 1).Value > 0 Then
numRows = numRows + 1
boolEmpty = False
ctr = ctr + 1
Else
'if true then exit while loop
boolEmpty = True
End If
Loop
ReDim tempArray1(numRows) ' Re-dimensionalize the array with the appropriate size
ReDim tempArray2(numRows) ' Re-dimensionalize the array with the appropriate size
'Fill tempArray1 & 2 with values
For i = 0 To numRows - 1
tempArray1(i) = Sheet6.Cells(i + 1, 1).Value
tempArray2(i) = Sheet6.Cells(i + 1, 2).Value
Next i
'Set variables
swapped = True
ctr = 0
'If swapped remains TRUE then continue sorting the array
Do While (swapped)
swapped = False
ctr = ctr + 1
'BUBBLE SORT
'Check if next element in array is bigger than the first one.
'If TRUE then swap the elements
'If FALSE then continue until looking through teh array until done.
For i = 0 To numRows - ctr
If tempArray2(i) > tempArray2(i + 1) Then
tmp1 = tempArray1(i)
tmp2 = tempArray2(i)
tempArray1(i) = tempArray1(i + 1)
tempArray2(i) = tempArray2(i + 1)
tempArray1(i + 1) = tmp1
tempArray2(i + 1) = tmp2
swapped = True
End If
Next i
Loop
'Redisplay the sorted array in excel sheet
For i = 0 To UBound(tempArray2)
Sheet6.Cells(i + 1, 1).Value = tempArray1(i)
Sheet6.Cells(i + 1, 2).Value = tempArray2(i)
Next i
End Sub
我这样做是为了一个按钮,因为如果你这样做,每次更改单元格时,你的 Excel 都会不断刷新选择更改事件的方式。但是,有一个解决方法。
在上面的例子中我使用了冒泡排序,你可以在网上的某个地方找到很多关于如何理解它的例子。
如果您希望我的代码正常工作,您将不得不更改我的 sheet6.cells(....
到
您的工作表编号,具体取决于您的列表在工作簿中的位置。
在“计算具有实际值的单元格数量...” 您必须将 ...Cells(ctr,1) 更改为您的列表所在的行和列索引。
希望我没有让你感到困惑。
这是我之前所说的另一种方式:
'If value has changed in column 2 then run macro
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column > 1 And Target.Column < 3 Then
MsgBox Target.Column
End If
End Sub
此代码需要在同一个工作表中。它会检查您更改的值是否实际上在第 2 列( Target.Column > 1 和 Target.Column
您看到 msgbox 的位置是您将复制并粘贴代码“冒泡排序等”的位置。
希望这会有所帮助。
【讨论】: