我编写了一个代码,它将我的所有工作表按升序和降序排序。现在请建议我应该如何修改代码,以便它只对我选择的几个特定工作表进行排序。 例如,如果我从总共10张纸中选择了纸张2,纸张5和纸张7,那么它应该按升序和降序排序这3张纸。
Sub Sort_Active_Book()
Dim i As Integer
Dim j As Integer
Dim iAnswer As VbMsgBoxResult
'
' Prompt the user as which direction they wish to
' sort the worksheets.
'
iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _
& "Clicking No will sort in Descending Order", _
vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")
For i = 1 To Sheets.Count
For j = 1 To Sheets.Count - 1
'
' If the answer is Yes, then sort in ascending order.
'
If iAnswer = vbYes Then
If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
'
' If the answer is No, then sort in descending order.
'
ElseIf iAnswer = vbNo Then
If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
End If
Next j
Next i
End Sub
我还为上述功能创建了一个Userform,请在下面找到:
Private Sub CommandButton1_Click()
Dim i As Integer
Dim j As Integer
Dim x As Long
Dim y As Long
Dim k As Long
Dim u As Long
Dim a As Long
Dim b As Long
If Me.OptionButton1 = True Then
' Prompt the user as which direction they wish to
' sort the worksheets.
For i = 1 To Sheets.Count
For j = 1 To Sheets.Count - 1
'
' sort in ascending order.
'
If Me.OptionButton3 = True Then
If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
'
' sort in descending order.
'
ElseIf Me.OptionButton4 = True Then
If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
End If
Next j
Next i
ElseIf Me.OptionButton2 = True Then
For i = 1 To Me.ListBox1.ListCount
For j = 1 To Me.ListBox1.ListCount - 1
If Me.ListBox1.Selected(j) = True Then
' sort in ascending order.
If Me.OptionButton3 = True Then
If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
' sort in descending order.
ElseIf Me.OptionButton4 = True Then
If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
End If
End If
Next
Next
End If
End Sub
Private Sub UserForm_Initialize()
Dim Sh As Variant
'for each loop the add visible sheets
For Each Sh In ActiveWorkbook.Sheets
If Sh.Visible = True Then
'add sheets to the listbox
Me.ListBox1.AddItem Sh.Name
End If
Next Sh
Me.OptionButton1 = True
End Sub
答案 0 :(得分:0)
关于代码的一个简单方法是检查在所有工作表中运行循环时是否选择了工作表。
答案 1 :(得分:0)
我会选择这样的东西。我没有测试过它:
Dim ss()
counter = 1
For Each x In ThisWorkbook.Windows(1).SelectedSheets
ReDim ss(1 To counter)
ss(counter) = x.Name
counter = counter + 1
Next
for i = 1 to ubound(ss)
for j = 1 to ubound(ss) - 1
...
...
...
next j
next i
在你的代码而不是Sheets(j).Name中写ss(j)而不是Sheets(j)写TishWorkbook.Sheets(ss(j))