2

我想检查 Excel2010 文档中是否存在格式样式。

On Error Resume Next

Private Function checkStyleName(ByVal strStyleName As String) As Boolean
    Dim objGivenStyle As Excel.Style

    Set objGivenStyle = ActiveDocument.Styles(strStyleName) ' try to get formatting style out of list
    If objGivenStyle Is Nothing Then
        ' do something
        checkStyleName = False
    Else
        checkStyleName = True
    End If
End Function

问题是,Set objGivenStlye = ActiveDocument.Styles(strStyleName)根本不起作用。最好的解决方案是什么——也许是所有现有样式的循环?

THX BKS

4

2 回答 2

3

现有的答案对我不起作用。这是一个有效的功能。它检查正在测试的样式名称是否存在并返回TRUEFALSE

Public Function StyleExists(ByVal styleName As String, ByVal target As Workbook) As Boolean
' Returns TRUE if the named style exists in the target workbook.
    On Error Resume Next
    StyleExists = Len(target.Styles(styleName).Name) > 0
    On Error GoTo 0
End Function

这是该函数的一个示例用法:

Sub test()
    MsgBox StyleExists("Normal", Activeworkbook) ' Should be TRUE.
    MsgBox StyleExists("Unusual", Activeworkbook) ' Should be FALSE unless custom style 'Unusual' is in the active workbook.
End Sub
于 2017-06-16T00:05:53.033 回答
1

这应该工作:

'case sensitive

Private Function checkStyleName(ByVal strStyleName As String) As Boolean
    Dim sCheck As String
    Dim wkb As Workbook

    checkStyleName = False
    Set wkb = ActiveWorkbook

    sCheck = "x" & strStyleName ' makes the two strings different
    On Error Resume Next
        sCheck = wkb.Styles(strStyleName).Name
    On Error GoTo 0

    If sCheck = strStyleName Then checkStyleName = True
End Function
于 2013-07-08T13:46:59.767 回答