本文記錄,如何使用 Word VBA,把文件中,長圖切割並拆分到多個頁中去。code
最近在處理一個 Word 文檔,發現裏面有特別長的圖片,超過了頁面大小,致使打印的時候,根本沒法打印整張圖片;而後發現,Word 中,根本沒有辦法,設置「圖片跨頁顯示」;並且在網上查了半天,也沒有好辦法;因而,只能本身動手豐衣足食了,寫段 VBA 代碼,專門用於處理這個問題;下面分享給你們;
orm
解決思路很簡單,就是根據頁面高度,對比圖片高度,要是圖片高度大於頁面高度,就按照頁面高度,把圖片切成一段一段的,放回去!
blog
代碼只能按照頁面高度,自動去切分,可是沒法肯定,切圖片的位置,剛好是你想要的位置;切完以後,要是須要微調切分位置,就用 Word 裏的 Crop 選項,本身手調吧。
圖片
VBA 中的 .Crop 方法,所截取的圖片的高度,是根據圖片原始尺寸計算的;因此,若是你有一個圖片,已經縮放了 40% 的高度;若是代碼中 .CropTop = 400,但因爲圖片有縮放,因此實際放到圖片上的 CropTop = 40% * 400,就變成了 160 了;這就致使,比你實際要剪裁的高度,少了不少;這就是爲何。我在代碼中,在剪裁高度上,逆向除回去了,縮放比例。
文檔
Sub Split_LongPic() ' Created by: Bitssea (https://www.cnblogs.com/bitssea/) Set o_InlineShape = ActiveDocument.InlineShapes(1) o_InlineShape.Select 'Find page height, deduct margin height Page_TopMargin = ActiveDocument.PageSetup.TopMargin Page_BottomMargin = ActiveDocument.PageSetup.BottomMargin Page_Height = ActiveDocument.PageSetup.PageHeight - Page_TopMargin - Page_BottomMargin - 20 'Find Shape Info, Scaled Height, Scale Percentage Shape_Height = o_InlineShape.Height Shape_ScalePercent = o_InlineShape.ScaleHeight / 100 If Shape_Height > Page_Height Then 'Find number of copy needed Split_No = Int(o_InlineShape.Height / Page_Height) + 1 For x = 1 To Split_No With o_InlineShape.PictureFormat 'Reset Pic Size .CropTop = 0 .CropBottom = Shape_Height 'Start Crop Pic .CropBottom = (Shape_Height - x * Page_Height) / Shape_ScalePercent .CropTop = ((x - 1) * Page_Height) / Shape_ScalePercent End With Selection.Copy Selection.Paste o_InlineShape.Select Next 'Delete orignal file, eliminate duplicate Selection.Delete End If End Sub
就這些,但願對你們有幫助,(^_^)bit