Word VBA代码改进

时间:2017-10-22 16:58:45

标签: ms-word word-vba

我正在编写一个代码来为用户输入书面问题添加颜色。我对vba相当新,代码工作正常但是我想改进它,即检测错误并且文件仍能正常运行的代码出错。

我有两种类型的输入,要么用户从下拉菜单中选择一些东西,要么写下他/她自己的答案(通常是数字,所以我有一个功能来修剪数字的答案,因为有字符)。

示例:

问:工作时数? 答:五(5)---->代码检查值(5)并在此基础上将“五(5)”颜色变为绿色。

感谢您的帮助。

Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As 
Boolean, Cancel As Boolean)

Dim store As String
Dim storeNum As Integer

 If ActiveDocument.Bookmarks.Exists("high") = True Then
    store = ActiveDocument.Bookmarks("high").Range.Text
    If store = "0" Then
        ActiveDocument.Bookmarks("high").Range.Font.TextColor = RGB(103, 106, 110)
    Else
        ActiveDocument.Bookmarks("high").Range.Font.TextColor = vbRed
    End If
 End If

If ActiveDocument.Bookmarks.Exists("medium") = True Then

 End If

 If (ActiveDocument.Bookmarks.Exists("bidders") = True) And (ActiveDocument.Bookmarks("bidders").Range.Text <> "Number of primary bids received and alternatives") Then
        storeNum = ExtractNumber(ActiveDocument.Bookmarks("bidders").Range)
        If storeNum > 7 Then
              ActiveDocument.Bookmarks("bidders").Range.Font.TextColor = RGB(0, 176, 80)
        ElseIf (storeNum > 3) And (storeNum < 8) Then
              ActiveDocument.Bookmarks("bidders").Range.Font.ColorIndex = wdDarkYellow
         ElseIf storeNum < 4 Then
            ActiveDocument.Bookmarks("bidders").Range.Font.TextColor = vbRed
         End If
    End If

    For Each oContentControl In ActiveDocument.ContentControls
    If oContentControl.Type = wdContentControlRichText Then
        oContentControl.Range.Font.Color = RGB(103, 106, 110)
        oContentControl.Range.Font.Name = "Trebuchet MS"
        oContentControl.Range.Font.Size = 11
        oContentControl.Application.ActiveDocument.Paragraphs.Alignment = wdAlignParagraphJustify
    End If
    Next
ActiveDocument.Fields.Update

End Sub

Function ExtractNumber(rCell As Range)
Dim iCount As Integer, i As Integer
Dim sText As String
Dim lNum As String


sText = rCell

For iCount = Len(sText) To 1 Step -1
    If IsNumeric(Mid(sText, iCount, 1)) Then
        i = i + 1
        lNum = Mid(sText, iCount, 1) & lNum
    End If

    If i = 1 Then lNum = CInt(Mid(lNum, 1, 1))
Next iCount

ExtractNumber = CLng(lNum)
End Function

1 个答案:

答案 0 :(得分:1)

嗯......这是一个广泛的问题,但仍有一些问题:

If (ActiveDocument.Bookmarks.Exists("bidders") = True) And ActiveDocument.Bookmarks("bidders").Range.Text <> "Number of primary bids 
received and alternatives") Then

因为评估了And的两个部分。换句话说,即使书签&#34;投标人&#34;如果不存在,您仍然要求生成错误的文本。

更好的方法是使用嵌套的If:

If (ActiveDocument.Bookmarks.Exists("bidders") = True) Then
    If ActiveDocument.Bookmarks("bidders").Range.Text <> "Number of primary bids received and alternatives") Then
        ' Your Code
    End If
End If

此If块为空(最好删除它):

If ActiveDocument.Bookmarks.Exists("medium") = True Then

End If

您可能也会遇到内容控件的问题,有时可能会锁定它们进行编辑,在这种情况下,当您尝试设置字体.name.color,{{{}时,您可能会遇到错误1}}。

您可以测试并设置内容控件是否已锁定:

.size