MS Word VBA: I need a color palette dialog box

后端 未结 2 748
迷失自我
迷失自我 2021-01-14 21:07

In VBA for MS Word 2010, how can I get Word to bring up a color palette dialog box so the user can pick a color?

There are tons of examples on how to do it

2条回答
  •  Happy的楠姐
    2021-01-14 21:43

    As far as I know Word does not have the same option as in Excel.
    Instead you can call a Windows inbuilt solution via .dll.
    I have recently created one in order to be able to pick more colors as text background color.

    Fisrtly the Windows documentation where you can see all the options you can modify:
    https://msdn.microsoft.com/en-us/library/windows/desktop/ms646830(v=vs.85).aspx
    Hint: CC_ANYCOLOR = 0x00000100 = &H100 (You need to use this form in VBA)

    From my code example you can see how to implement it:
    This goes top of Module:

    Private Type CHOOSECOLORSTRUCT
       lStructSize     As Long
       hwndOwner       As Long
       hInstance       As Long
       rgbResult       As Long
       lpCustColors    As Long
       flags           As Long
       lCustData       As Long
       lpfnHook        As Long
       lpTemplateName  As String
    End Type
    
    Private Declare Function ChooseColor Lib "comdlg32.dll" _
       Alias "ChooseColorA" _
      (lpcc As CHOOSECOLORSTRUCT) As Long
    

    This is the picker caller function with optionally submitted OriginalColor:

    Public Function PickColor(Optional OriginalColor As Variant = 8421376) 'You can define any colour as default instead of 8421376)
        Dim cc As CHOOSECOLORSTRUCT
        Dim dwCustClrs(0 To 15) As Long
    
        With cc
            .Flags = &H100 Or &H1 Or &H2
            .lStructSize = Len(cc)
            .hwndOwner = 0
            .lpCustColors = VarPtr(dwCustClrs(0))
            .rgbResult = OriginalColor
        End With
    
        If CHOOSECOLOR(cc) = 1 Then
            PickColor = cc.rgbResult
        End If
    End Function
    

    And finally this is how you call it in action:

    Sub F_HáttérSzínVálasztó()
        With Selection.Font.Shading
            .BackgroundPatternColor = PickColor(Selection.Font.Shading.BackgroundPatternColor)
        End With
    End Sub
    

提交回复
热议问题