lundi 21 novembre 2016

Inserting a checkbox in word VBA

Hi I have the following code to insert a checkbox in word VBA; basically it draws information from a spreadsheet where there are certain columns (I've only included 19, but there are at least 15 more) that are 'questions'; meaning, a checkbox needs to be inserted, and how that question is answered it is either checked or not checked.

Other than that, it fills out information which is in the format of either string or number; but it's always inserted at the next bookmark.

In the word document, there are a series of bookmarks, labeled iteratively. Meaning, from the start of the document, the first bookmark is named bm1, then bm2, to bm 61.

The issue is the inserting of the checkbox. The following code inserts the checkbox! But then word gives the error:

Error 438 - object doesn't support this property or method. But it inserts!

How to work through this error?

 Sub WriteExtension()

    'initialize excel variables
    Dim bmrange As Range

    'initialize excel objects
    Dim oExcel As Excel.Application
    Dim oWorkbook As workbook
    Dim oWorksheet As worksheet

    'start up this instance of excel
    Set oExcel = New Excel.Application
    Set oWorkbook = oExcel.Workbooks.Open("C:\file\path\here")
    Set oWorksheet = oWorkbook.Worksheets(Sheets("Extensions").Index)

    'stores whatever is in the spreadsheet cell
    Dim tempString As String 

   For i = 7 To 61
        'store the current item in worksheet
        tempString = oWorksheet.Cells(4, i)

        'set the range of the current bookmark being iterated through
        Set bmrange = ActiveDocument.Bookmarks("BM" & (i - 6)).Range


        'put in a checkbox
        If i = 19 Then
            'cast it as an int; the value in the spreadsheet is either 1 or 0 
 'at cell(4, 19)
            If CInt(tempString) = 1 Then
                ActiveDocument.Range.InsertAfter    (ActiveDocument.ContentControls.Add(wdContentControlCheckBox, bmrange).Checked)
                Set bmrange = ActiveDocument.Bookmarks("BM" & (i + 1 - 6)).Range
                ActiveDocument.Range.InsertAfter (ActiveDocument.ContentControls.Add(wdContentControlCheckBox, bmrange))
                i = i + 2
            Else
                ActiveDocument.Range.InsertAfter (ActiveDocument.ContentControls.Add(wdContentControlCheckBox, bmrange))
                Set bmrange = ActiveDocument.Bookmarks("BM" & (i + 1 - 6)).Range
                ActiveDocument.Range.InsertAfter (ActiveDocument.ContentControls.Add(wdContentControlCheckBox, bmrange).Checked)
                i = i + 2
            End If

        Else

            ActiveDocument.Bookmarks("BM" & (i - 6)).Range.InsertAfter (tempString)
        End If


    Next i

 end sub




Aucun commentaire:

Enregistrer un commentaire