This code works up to the start of the second iteration where SelectedArray(i) = 1 (this array can only take the values 0 or 1), then it crashes. How do I fix it?
The problem is that this all works fine for the first value of i for which SelectedArray(i) = 1 [members of SelectedArray can only take the values 0 or 1, this links up with the checkboxes the user has selected in the userform] but if the user selects two (or more) checkboxes, the routine crashes on its second pass.Code:For i = 1 To big_deep If SelectedArray(i) = 1 Then Set wrdApp = CreateObject("Word.Application") wrdApp.Visible = True Set wrdDoc = wrdApp.Documents.Open("C:\My Documents\Geek Stuff\Document for Office Holder.doc") wrdDoc.Activate With wrdDoc ' code that defines position_name & other stuff ActiveDocument.Bookmarks("offr_name").Range.InsertBefore position_name ' more code to populate document here If Dir(ActiveWorkbook.Path & "\" & position_name & ".doc") <> "" Then Kill ActiveWorkbook.Path & "\" & position_name & ".doc" End If .SaveAs (ActiveWorkbook.Path & "\" & Left(position_name, 20) & ".doc") .Close ' close the document End With wrdApp.Documents.Open ("C:\My Documents\Geek Stuff\Document for Office Holder.doc") For Each wrdDoc In Documents wrdDoc.Close SaveChanges:=wdSaveChanges Next wrdDoc ' wrdApp.Close wrdApp.Quit oXLSheet.Cells(i + 2, big_wide + 2).Select oXLSheet.Cells(i + 2, big_wide + 2).Value = Format(Date, "d-mmm-yy") MsgBox ("Document for " & position_name & " created") ' _________________________________________ end of creation of new doc End If ActiveWorkbook.Save Next i End Sub
The code that the routine doesn't like is the line:
and the problem it claims it has is that there is no word document open, although in fact there is. (I inserted the message box down towards the end and also the save command to let the routine catch up with itself, but that doesn't fix the problem.)Code:ActiveDocument.Bookmarks("offr_name").Range.InsertBefore position_name
(This code is being run from an excel file, hence the need to open an instance of Word.)
Thanks




Reply With Quote