(免責事項:私は職業によってVBAプログラマーではない)
リボンのボタンに添付されている私はWord文書の会社のロゴを切り替えるコードがあります。
ロゴタイプAの1つのボタン、ロゴタイプBの2番目のボタン、ロゴなしの3番目のボタン(ロゴは紙にプレプリントされています)
最初に removeLogo
でロゴを削除してから、 setLogoAt
でリクエストされたロゴを追加します。
最初のボタンクリックは良好です(ロゴタイプAなど)。ロゴがドキュメントのヘッダーに追加されます。他のボタン(ロゴタイプBなど)をクリックすると、Wordがクラッシュする(おそらく現在のロゴを削除している)
私のコードで何が間違っているのですか?
Sub setLogoAt(left As Integer, path As String)
Dim logoShape As Shape
Dim anchorLocation As Range
Dim headerShapes As Shapes
Set logoShape = ActiveDocument. 'linebreks for readability
.Sections(1)
.Headers(wdHeaderFooterPrimary)
.Shapes
.AddPicture(FileName:=path, LinkToFile:=False,
SaveWithDocument:=True, left:=0,
Top:=0, Width:=100, Height:=80)
logoShape.name = "CompanyLogo"
logoShape.RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
logoShape.RelativeVerticalPosition = wdRelativeVerticalPositionPage
logoShape.Top = CentimetersToPoints(0.1)
logoShape.left = CentimetersToPoints(left)
End Sub
Sub removeLogo()
Dim headerShapes As Shapes
Set headerShapes = ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Shapes
Dim shapeToDelete As Shape
If (headerShapes.Count > 0) Then
If Not IsNull(headerShapes("CompanyLogo")) Then
Set shapeToDelete = headerShapes("CompanyLogo")
End If
End If
If Not (shapeToDelete Is Nothing) Then
shapeToDelete.Delete
End If
End Sub
編集
私は自分のコードを歩きました。 removeLogo
の行 shapteToDelete.Delete
に達するまでは問題ありません。ここでは、Wordは、たとえデバッグ中であってもハードにクラッシュします。私は Word 2007 を使用しています(それは要件です)
edit2
I cleared all macros, all normals.dot, all autoloading templates, then created a new document with the two routines above and this test method:
Sub test()
setLogoAt 5, "C:\path\to\logo.jpg"
removeLogo
setLogoAt 6, "C:\path\to\logo.jpg"
End Sub
test
を実行すると、 removeLogo
の shapeToDelete.Delete
でクラッシュします。
Edit 3
I 'solved' the problem by first making the headers/footers view the active view in Word, then deleting the Shape and then returning to normal view. Very strange. It works but as a programmer I'm not happy.