(免责声明:我不按职业划分的VBA程序员)
附加到功能区中的按钮我有代码可以在Word文档中切换公司徽标。 一个按钮用于徽标类型A,第二个按钮用于徽标类型B,第三个按钮用于没有徽标(徽标是预先打印在纸上)
首先,我使用removeLogo
删除徽标,然后使用setLogoAt
添加所请求的徽标。
第一次按钮点击很好(例如,对于徽标类型A),徽标被添加到文档的标题中。当我点击另一个按钮(例如徽标类型B)时,Word崩溃(可能是删除当前徽标)
我的代码有什么问题(或者不太可能:使用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
修改
我踏上了我的代码。一切正常,直到我到达shapteToDelete.Delete
中的removeLogo
行。即使在调试时,Word也很难崩溃。我正在使用 Word 2007 (这是一项要求)
EDIT2 我清除了所有宏,所有normals.dot,所有自动加载模板,然后使用上面的两个例程和这个测试方法创建了一个新文档:
Sub test()
setLogoAt 5, "C:\path\to\logo.jpg"
removeLogo
setLogoAt 6, "C:\path\to\logo.jpg"
End Sub
当我运行test
时,它会在removeLogo
shapeToDelete.Delete
处崩溃。
编辑3 我通过首先使页眉/页脚在Word中查看活动视图,然后删除Shape然后返回到普通视图来解决问题。很奇怪。它有效,但作为程序员,我不高兴。
答案 0 :(得分:1)
另一个可能的解决方案是首先尝试选择形状,然后删除选择:
shapeToDelete.Select Selection.Delete
如果可行的话,你可能想要关闭屏幕更新,否则当Word在文档中移动时你会闪烁。
答案 1 :(得分:0)
我之前遇到过这个问题,并且通常会出现自动化错误:“调用的对象已与其客户端断开连接”。我还没有找到解决方案。
然而,一个好的解决方法是隐藏形状而不是删除它。
所以:
shapeToDelete.Visible = False
答案 2 :(得分:-1)
这有效: 我只有2个盒子可以隐藏,所以这不是通用的
Private Sub btnPrint_Click()
Dim hdrShapes As Shapes
Dim S As Shape
Dim aTohide(2) As String
Dim iNdx, i As Integer
iNdx = 0
' Hide buttons and print
Set hdrShapes = ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Shapes
' GET BUTTON NAMES (ACTUALLY TEXT BOXES
For Each S In hdrShapes
If S.Type = msoTextBox Then
aTohide(iNdx) = S.Name
iNdx = iNdx + 1
End If
Next
' now hide , use the arrays as the for each statement crashes
For i = 0 To 1
hdrShapes(aTohide(i)).Visible = msoFalse
Next
' print it
With ActiveDocument
.PrintOut
End With
' and unhide the buttons
For i = 0 To 1
hdrShapes(aTohide(i)).Visible = msoTrue
Next
Set hdrShapes = Nothing
End Sub