gpt4 book ai didi

excel - 如何在 For Each 循环之外创建一个 vbYesNo MsgBox?

转载 作者:行者123 更新时间:2023-12-03 21:43:01 25 4
gpt4 key购买 nike

我正在尝试做的事情:
如果存在未命名为“宏”的工作表 > 使用 MsgBox 提示用户 > 如果是,则删除所有未命名为“宏”的工作表
但只显示 MsgBox 一次 (如果存在多于 1 个工作表,则不显示每个工作表的 MsgBox)
当前代码有问题:
当“宏”是唯一存在的工作表时,仍然会收到 MsgBox 提示。
当前代码:

Sub reset()

Dim conditionMet As Boolean
Dim answer As Integer

conditionMet = FALSE
answer = MsgBox("There Is already data here. Click Yes To delete reset macro.", vbQuestion + vbYesNo)

Application.DisplayAlerts = FALSE

For Each Sheet In ThisWorkbook.Worksheets
If Sheet.Name <> "Macro" Then
conditionMet = TRUE
Else
Exit Sub
End If
Next Sheet

If conditionMet Then
If answer = vbYes Then
Sheet.Delete
Else
Exit Sub
End If
Else
Exit Sub
End If

Application.DisplayAlerts = TRUE

End Sub

最佳答案

这是一种方法:

Const KEEP_THIS As String = "Macro"
Dim ws As Worksheet

On Error Resume Next
Set ws = ThisWorkbook.Sheets(KEEP_THIS)
On Error GoTo 0
If ws Is Nothing Or ThisWorkbook.Worksheets.Count = 1 Then Exit Sub 'no "Macro" sheet

If MsgBox("Delete all data sheets?", vbQuestion + vbYesNo) <> vbYes Then Exit Sub
'remove all non-Macro sheets
For i = ThisWorkbook.Worksheets.Count To 1 Step -1
With ThisWorkbook.Worksheets(i)
If .Name <> KEEP_THIS Then .Delete
End With
Next i

关于excel - 如何在 For Each 循环之外创建一个 vbYesNo MsgBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66270204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com