我修改了一个Word文档,添加了4个ComboBox,每个都有一些下拉选项。它工作正常,除非用户删除包含其中一个ComboBox的文档部分。如果他们这样做,当他们重新打开文档时,他们会得到"编译错误:找不到方法或数据成员"
有没有办法可以添加代码来检查ComboBox是否存在于打开文档并执行代码或忽略它?我已尝试使用" On Error Resume Next"无济于事。
以下是代码片段:
headers
如果用户删除了ComboBox2,则重新打开文档 - 它会弹出并获取该错误。
谢谢!
答案 0 :(得分:0)
下面的代码是用Word 2010编写的。但是,我相信它也可以在Word 365上顺利运行。它应该粘贴到您的VBA项目的ThisDocument
模块中。
Option Explicit
Private Sub Document_Open()
' 10 Nov 2017
Dim Cn As String ' control name
Dim i As Integer
Dim MissingControl As Boolean
Dim Msg As String
For i = 1 To 2
Cn = "ComboBox" & i
If Not ShapeExists(Cn) Then
MissingControl = True
Exit For
End If
Next i
If MissingControl Then
MsgBox Cn & " doesn't exist", _
vbInformation, "Corrupted document"
Exit Sub
Else
With ActiveDocument
With .ComboBox2
.List = Array("Choose One", "SSN", "Employee ID")
If .ListIndex < 0 Then .ListIndex = 0
End With
End With
End If
End Sub
Private Sub ComboBox2_Change()
' 10 Nov 2017
Dim Msg As String
Msg = IIf(ComboBox2.ListIndex = 2, _
"Employee ID must be unique by employee and " & _
"all numeric with a max of 9 digits.", "")
TextBox3.Value = Msg
End Sub
Private Function ShapeExists(Cn As String) As Boolean
' 10 Nov 2017
Dim Shp As InlineShape
Dim i As Integer
For Each Shp In ActiveDocument.InlineShapes
If StrComp(Shp.OLEFormat.Object.Name, Cn, vbTextCompare) = 0 Then
ShapeExists = True
Exit For
End If
Next Shp
End Function
观察到设置ComboBox2列表时会发生ComboBox2_Change
事件。但是,ListIndex将为0,这将导致清除TextBox3。更改ComboBox2的值时将显示消息文本。