我在网上找到了这个代码,它几乎完全符合我的要求。目前,它提供了工作簿中的工作表列表(在用户表单中),然后我可以选择要删除的工作表(通过复选框),并保留未选择的工作表。
我希望它与此相反:选择我想要保留的工作表并删除未选择的工作表。
Option Explicit
'thanks domenic mrexcel mvp
Private Sub SubmitButton_Click()
Dim MyArray() As Variant
Dim i As Long
Dim Cnt As Long
With Me.ListBox1
Cnt = 0
For i = 0 To .ListCount - 1
If .Selected(i) Then
Cnt = Cnt + 1
ReDim Preserve MyArray(1 To Cnt)
MyArray(Cnt) = .List(i)
End If
Next i
If Cnt > 0 Then
If Worksheets.Count > UBound(MyArray) Then
Application.DisplayAlerts = False
Worksheets(MyArray).Delete
Application.DisplayAlerts = True
Call UpdateSheetList
Else
MsgBox "A workbook must contain at least one visible sheet.", vbExclamation
End If
Else
MsgBox "Please select one or more sheets for deletion...", vbExclamation
End If
End With
End Sub
Private Sub CancelButton_Click()
'unload form
Unload Me
End Sub
Private Sub UserForm_Initialize()
Call UpdateSheetList
End Sub
Private Sub UpdateSheetList()
Dim wks As Worksheet
With Me.ListBox1
.Clear
For Each wks In Worksheets
.AddItem wks.Name
Next wks
End With
End Sub
答案 0 :(得分:2)
尝试将代码的此部分从True更改为False
For i = 0 To .ListCount - 1
'Change the next line
If .Selected(i) = False Then
Cnt = Cnt + 1
ReDim Preserve MyArray(1 To Cnt)
MyArray(Cnt) = .List(i)
End If
Next i