Logo

dev-resources.site

for different kinds of informations.

Word VBA 刪除所有圖形

Published at
9/18/2024
Categories
vba
word
Author
codemee
Categories
2 categories in total
vba
open
word
open
Author
7 person written this
codemee
open
Word VBA 刪除所有圖形

因為工作的需要, 所以問了 Claude 如何使用 VBA 刪除文件內所有的圖形, 於是得到了這樣的解法:

Sub 移除繪圖物件()
    Dim shp As shape

    For Each shp In ActiveDocument.Shapes
        shp.Delete
    Next shp

    MsgBox "所有圖形物件已被刪除。", vbInformation
End Sub
Enter fullscreen mode Exit fullscreen mode

實際運作的確可以刪除所有的圖形, 只是有個想問題, 我得重複執行好幾次才能刪掉所有的圖形, 再次詢問 Clause, 它以為我是沒有刪除 InlineShapes 集合的圖形。改問 Microsoft Copilot 後, 提醒了我, 因為這個集合是動態的, 上述解法會導致集合內的項目數量變化, 原本要取出的下一個項目的索引值變了, 例如本來在索引位置 2 的項目, 因為索引位置 1 的項目被刪除了, 現在變成索引 1, 如果還是取索引項目 2 的項目, 就會是最開始索引項目 3 的項目, 遺漏了本來要取出的項目:

index  1  2  3
     |20| 7|45|
      -- -- --

刪除 20 後:

index  1  2  3
     | 7|45|
      -- -- --
Enter fullscreen mode Exit fullscreen mode

應該要直接以倒序的方法使用索引取值的方式刪除才不會有問題:

Sub 移除繪圖物件()
    For i = ActiveDocument.Shapes.Count To 1 Step -1
        ActiveDocument.Shapes(i).Delete
    Next i

    MsgBox "所有圖形物件已被刪除。", vbInformation
End Sub
Enter fullscreen mode Exit fullscreen mode
vba Article's
30 articles in total
Favicon
mala direta usando o VBA, Excel e Word tudo juntos
Favicon
Custom Inventory Management System Using VBA: A Cost-Effective Solution for Small Businesses
Favicon
Import objects from another database in Access VBA
Favicon
Excel 基礎 Part 03 -- 作成したマクロ関数を開発タブから実行する
Favicon
Validate date format in VBA
Favicon
Connect MS Access to SQL Server using ADO
Favicon
Calculate elapsed time in milliseconds in VBA
Favicon
Word VBA 刪除所有圖形
Favicon
How to implement a Polar Area Chart using VBA
Favicon
Automating Excel with Power: Building Your Own Plugin using VBA
Favicon
Outputting data without using a loop
Favicon
How to do Excel table association – You are out if you know only VLOOKUP
Favicon
SPL XLL Practice: Almighty Text Splitting in Excel
Favicon
SPL XLL Practice: Excel Interval Association
Favicon
Excel Advanced Group and Summary Method
Favicon
How to Automatically Extract Eligible Rows in Excel
Favicon
Set operations of Excel inter row data (intersection, union, difference)
Favicon
Power Apps - VBA Subs and Functions
Favicon
Hello there ..im looking for help from someone who has knowledge about VbA
Favicon
How to Merge Excel Sheets Horizontally
Favicon
What Programming Language Should Business People Learn?
Favicon
Looking for Advanced Excel, VBA & Macros Course in Mumbai
Favicon
How to Save Multiple Excel Files into the Same Folder
Favicon
New 64-bit IDE for VB6 developers,Twinbasic VisualFreebasic
Favicon
Streamlining Your Work with Custom Excel Functions
Favicon
Separação de conteúdo em arquivos no Microsoft Excel
Favicon
在 VBA 中讀取 UTF8 編碼的文字檔
Favicon
VBA and Excel as an office GUI.
Favicon
Send an SMS Message From an Excel Spreadsheet
Favicon
在 Office VBA 使用 Open AI API

Featured ones: