View Single Post
 
Old 04-11-2013, 03:59 AM
thecreaser thecreaser is offline Windows 7 32bit Office 2010 32bit
Novice
 
Join Date: Mar 2013
Posts: 5
thecreaser is on a distinguished road
Default

I like the idea of deleting the content control. You're right, we don't have a need to change the values later.

I'm getting an error using the .ContentControls (1):
The requested member of the collection does not exist
Any ideas?

As a total vba novice I'm inching slowly forward. What is the significance of the (1) ?

My hideously badly written code is:

Code:
Sub Populate_Word_Template()
'create copy of Word in memory
Dim doc As Word.Document
Dim iResponse As VbMsgBoxResult
Dim JRNumberRange As Range
wd.Visible = True


'get the Job Request number from the excel table
On Error Resume Next
    Application.DisplayAlerts = False
        Set JRNumberCell = Application.InputBox(Prompt:= _
            "Please click cell of JR number", _
                Title:="SPECIFY JOB REQUEST NO.", Type:=8)
                'Type=8 means cell reference is expected
On Error GoTo 0
    Application.DisplayAlerts = True
    If JRNumberCell Is Nothing Then
        Exit Sub
    Else
        MsgBox "JR number " & JRNumberCell & " was selected"
    End If
    
'check whether the Job Request file exists already
If Dir(FilePath & JRNumberCell.Value & ".docx") <> "" Then
    'ask what to do
    iResponse = MsgBox(FilePath & JRNumberCell.Value & ".docx already exists. OK to overwrite or Cancel to stop macro.", _
                vbOKCancel + vbQuestion + vbDefaultButton2 + vbMsgBoxSetForeground, _
                Title:="OVERWRITE EXISTING FILE?")
    If iResponse = vbCancel Then Exit Sub
        'otherwise OK carry on with macro
    MsgBox "You've chosen to overwrite an existing file"
End If
    
Set doc = wd.Documents.Open(FilePath & "job request form.dotx")
    
'go to each bookmark and type in details by calling sub CopyCell
CopyCell "JRNumber", 0 '0 columns offset from 1st column
CopyCell "MSSHrsEstimate", 9
CopyCell "ProjectCode", 2
CopyCell "DateOfRequest", 7
CopyCell "DateRequiredBy", 8
'delete the content control from the word file
With doc.Tables(1).Cell(4, 2).Range
    .ContentControls(1).LockContentControl = False
    .ContentControls(1).Delete
End With
CopyCell "Requestor", 6
CopyCell "AuthorisedBy", 5
CopyCell "Project", 3
CopyCell "Product", 4

'save the Word document
doc.SaveAs FilePath & JRNumberCell.Value & ".docx", FileFormat:=wdFormatXMLDocument
MsgBox "Saved file " & FilePath & JRNumberCell.Value & ".docx and left it open for you to edit"
'close the Word document
'doc.Close

'quit word
'wd.Quit

End Sub

Sub CopyCell(BookMarkName As String, ColumnOffset As Integer)
'copy each cell to relevant Word bookmark

wd.Selection.GoTo What:=wdGoToBookmark, Name:=BookMarkName
wd.Selection.TypeText JRNumberCell.Offset(0, ColumnOffset).Value
End Sub
Any words of wisdom would be appreciated.
Reply With Quote