如何处理VB中的此运行时类型不匹配错误?

时间:2019-05-16 11:08:22

标签: vba ms-word

我在MS Word中有一个表,该表包括下拉列表项以及根据所选下拉列表项的组合显示和输出值的列。在集合中仅选择一个下拉列表项时,出现“运行时错误'13'类型不匹配”错误。

我将如何处理此错误?

注意:如果仅选择一个,然后用户单击鼠标,则每组中都有两个下拉列表。我希望结果列恢复为默认值,即不显示任何内容。

我知道这应该在Excel中完成,但不幸的是,我必须处理已有的东西。

如果在单击之前选择了非默认项目,我的代码将正常工作,并且不会产生任何错误。但是,如果仅选择了一个下拉列表中的一项,而另一个下拉列表的值保留为默认值,则会显示错误。

如果我尝试取消选择下拉列表项之一而不是全部取消选择,也会显示错误。

运行时错误“ 13” 类型不匹配

Private Sub Document_ContentControlOnExit(ByVal CC As ContentControl, Cancel As Boolean)
Dim CField As String, LField As String, RField As String, CText As String, LText As String, CRate As Double, LRate As Double, RRate As Double, RCat As String, RCatField As String
Select Case CC.Title
Case "C1", "L1"
CField = "C1"
LField = "L1"
RField = "R1"
RCatField = "RR1"

Case "C2", "L2"
CField = "C2"
LField = "L2"
RField = "R2"
RCatField = "RR2"


Case Else
Exit Sub
End Select

CText = Left(ActiveDocument.SelectContentControlsByTitle(CField).Item(1).Range.Text, 1)
LText = Left(ActiveDocument.SelectContentControlsByTitle(LField).Item(1).Range.Text, 1)
    If Not IsNumeric(CText) Then
With ActiveDocument.SelectContentControlsByTitle(RField)(1)
   .LockContents = False
   .Range.Text = ""
   .LockContents = True
End With
With ActiveDocument.SelectContentControlsByTitle(RCatField)(1)
   .LockContents = False
   .Range.Text = ""
   .LockContents = True
End With
      End If
        If Not IsNumeric(LText) Then
      Exit Sub
      End If
      LRate = LText
      CRate = CText
      RRate = ((CRate * 3) + (LRate * 2)) * 4
      Select Case RRate
      Case Is < 41
      RCat = "Low"
      Case Is < 55
      RCat = "Moderate"
      Case Is < 70
      RCat = "High"
      Case Is >= 70
        RCat = "Catastrophic"
      End Select




With ActiveDocument.SelectContentControlsByTitle(RField)(1)
   .LockContents = False
   .Range.Text = RRate
   .LockContents = True
End With
With ActiveDocument.SelectContentControlsByTitle(RCatField)(1)
   .LockContents = False
   .Range.Text = RCat
   .LockContents = True
End With
End Sub

1 个答案:

答案 0 :(得分:-1)

您可以在代码中添加错误处理程序。添加

On Error GoTo errHandlr

发生错误的位置。 稍后,定义发生错误时应该发生的情况:

errHandlr:
   Debug.Print Err.Number & ":-:" & Err.Description

If Err.Number = 13 Then
    wsChange
End if

Public Function wsChange(ByVal As Range) 

  If Target.Address ="$A$1"' range of drop down list
  Range("A1").Value = "Your default  value."    'A1 should be your drop down   list address.

  End if
End sub