Use a variable to select an ActiveX control Checkbox by name (in Word from Excel)?

末鹿安然 提交于 2019-12-11 01:38:47

问题


What is wrong with this line of code?

WordDoc.CheckBoxNum.Value = CheckBoxVal

To be clear, I am working with an ActiveX control "Checkbox". I have the values (true/false) and checkbox names saved in an Excel file. The code opens my word document and automatically loops through the checkboxes, setting their values. The fact I am controlling word from Excel may change my objects?

If they were Form Field... This works--

CheckBoxNum = "Check1"
CheckBoxVal = "True"
WordDoc.FormFields(CheckBoxNum).CheckBox.Value = CheckBoxVal

Here is my whole code

Sub Doit()
    Dim WordApp As Object
    Dim WordDoc As Object
    Dim filepath As String
    Dim CheckBoxNum As String
    Dim CheckBoxVal As String
    Dim i As Integer, k As Integer

    'Open Word
    filepath = "C:\test.docx"
    Set WordApp = CreateObject("word.application")
    WordApp.Visible = True
    Set WordDoc = WordApp.Documents.Open(filepath)

    'Editing
    Range("a1").Select 'first value
    i = 0
    For i = 0 To 6 ' number of rows in table 
          'get from excel
          CheckBoxNum = ActiveCell.Offset(i, k + 1).Value
          CheckBoxVal = ActiveCell.Offset(i, k).Value

           'put to word
           WordDoc.CheckBoxNum.Value = CheckBoxVal '<-- HELP!
    Next i

    '// CLEAN UP //
    WordDoc.Application.ActiveDocument.Save
    WordDoc.Close
    WordApp.Quit
    Set WordDoc = Nothing
    Set WordApp = Nothing
End Sub

回答1:


Unfortunately we cannot refer to an ActiveX control directly by its name using WordDoc.InlineShapes(CheckBoxNum), this only works if we know its index number: WordDoc.InlineShapes(1).

This means that you have to loop through all the controls, comparing its OLEFormat.Object.Name to the name you are looking for:

Dim obj As Object

For i = 0 To 6 ' number of rows in table
    'get from excel
    CheckBoxNum = ActiveCell.Offset(i, k + 1).Value
    CheckBoxVal = ActiveCell.Offset(i, k).Value

    For Each obj In WordDoc.InlineShapes
        If obj.OLEFormat.Object.Name = CheckBoxNum Then
            obj.OLEFormat.Object.Value = CheckBoxVal
        End If
    Next obj
Next i



回答2:


AFAIK, you can use:

WordDoc.InlineShapes(CheckBoxNum).OLEFormat.Object.Value = CheckBoxVal


来源:https://stackoverflow.com/questions/24088721/use-a-variable-to-select-an-activex-control-checkbox-by-name-in-word-from-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!