背景:
-
win10, excel 打开 wps 生成的 xlsx文档;
-
文档中有多余的图形,经检测为shape大类;
-
文档中可见的图形可以全选后删除; 但是不可见部分仍然存在;
-
vba删除时,可以直接循环删除,类似 shape.delete;
-
vba删除前,如果逐一选择(shape.select)以便查看,则出现多种错误(vba运行异常),但都是运行时错误
错误记录:
- 类型多样:用shape.name查看,有以下类别:
1)comment;在visible=false情况下,错误信息为-2147467259-自动化 (Automation) 错误
2)代表picture的长串字母-数字;
3)host control x;在visible=false情况下,错误信息为-2147024809-请求的图形已被锁定供选择
-
经检查,图形(shapes)中有一部分是不可见的,无法选中即不能用shape.select选择;
-
将不可见图形设置为可见后,则问题解决
解决思路及代码如下:
-
思路,倒循环, 设置为可见,删除
-
代码如下:
Public Sub shape_remove()
'wps xlsx文档,用excel打开后,有多余的图形(shape)出现而在wps中没有
'try to keep previous err file
If ActiveSheet.Shapes.Count = 0 Then
Debug.Print "no shapes"
End
End If
'test only
Open ActiveWorkbook.Path & "\err.txt" For Output As #1
'main
For i = ActiveSheet.Shapes.Count To 1 Step -1
Set sp = ActiveSheet.Shapes(i)
On Error Resume Next
sp.Select
Print #1, "i=" & i, "shape name:" & sp.Name
Print #1, "shape type name:" & TypeName(sp)
Print #1, "visible=" & CBool(sp.Visible)
If Err.Number <> 0 Then
Print #1, "Err:" & Err.Number & "-" & Err.Description
If sp.Visible = 0 Then
Print #1, i & " not visible."
sp.Visible = True
Print #1, "set to visible"
i = i + 1
sp.Select 'for shape details check
End If
Else
Print #1, "selected and deleted"
Selection.Delete
End If
On Error GoTo 0
Print #1, Chr(13)
Next
'test only
Close #1
End Sub