gpt4 book ai didi

excel - 找不到VBA消息自动化错误元素

转载 作者:行者123 更新时间:2023-12-03 08:20:57 27 4
gpt4 key购买 nike

我有一本使用宏并制作许多图纸的工作簿。在使用一张名为“粘贴”的工作表之后,我希望能够在使用完后删除后面的工作表。

我从https://stackoverflow.com/a/53544169/11615632找到了以下代码,并对其进行了少许修改以在我的工作簿中使用。

Sub Deleting()
Dim Indx As Long
Dim x As Long

With ThisWorkbook
On Error Resume Next
Indx = .Sheets("Paste").Index
On Error GoTo 0

If Indx <> 1 Then
If .Sheets.Count > 2 And Indx < .Sheets.Count Then
Application.DisplayAlerts = False
For x = .Sheets.Count To Indx + 1 Step -1
.Sheets(x).Delete

On Error GoTo 0
Next x
Application.DisplayAlerts = False
End If
Elseif Indx = 1 Then
Exit Sub
End If
End With
End Sub

但是,当我这样做时它确实有效,但是我收到一条错误消息,提示

"Run-time error '-2147319765':
Automation Error
Element not found.



.Sheets(x).Delete行上发现错误

最佳答案

由于您知道要保留两个特定的工作表(“值”和“粘贴”),而不是使用索引,这可能会有些棘手,并且根据它们的顺序/添加的顺序可能并不总是有效,因此建议而是查看每个工作表的名称并以这种方式删除(如注释中所述)。

Dim ws as Worksheet
' This next line will suppress the "Confirm Deleting" messagebox
' when you go to delete a worksheet
Application.DisplayAlerts = False
For each ws in ThisWorkbook.Worksheets
If ws.Name <> "Value" and ws.Name <> "Paste" Then
ws.Delete
End If
Next ws
Application.DisplayAlerts = True

(这假定宏存储在您要从中删除工作表的工作簿中。如果不是,则可能存储在Personal.xlsb中,然后将 ThisWorkbook切换为 ActiveWorkbook或更具体。)

关于excel - 找不到VBA消息自动化错误元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57190019/

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