# Excel to Word doc / File Patch -> cell



## beczer (Nov 21, 2016)

Hi there

I am not advanced Vba programmer and I need your help. Could please review my code and tell how to change the DOC(template) file path ? In other words, I would like to use 3 different word templates so I can't put file path in VBA code as it is. I need to put a reference to cell where there is a file path.
A1 - C:\Users\Tom\Desktop\doc1.docx
A2 - C:\Users\Tom\Desktop\doc2.docx
A3 - C:\Users\Tom\Desktop\doc1.docx

Another thing, I would also like to add a possiblity to save DOCs and PDFs in created folder by VBA. 

My current VBA code:


```
Sub CreateWordTemplate()




    Dim wdApp As Word.Application
    Dim SaveName As String
    Dim FileExt As String
    Set wdApp = CreateObject("Word.Application")


    With wdApp
        '.Visible = True
        '.Activate
        
        .Documents.Add "C:\Users\name\Desktop\doc1.docx"




    Range("A1", Range("A1").End(xlDown).End(xlToRight)).Copy
        
    
    .Selection.GoTo What:=-1, Name:="bookmark1"
    .Selection.PasteSpecial


FileExt = ".pdf"
                            
                 SaveName = Environ("UserProfile") & "\Desktop\doc1.docx " & _
        Format(Now, "yyyy-mm-dd hh-mm-ss") & ".pdf"




                .ActiveDocument.ExportAsFixedFormat OutputFileName:=SaveName, ExportFormat:=17
              
        
       SaveName = Environ("UserProfile") & "\Desktop\doc1.docx " & _
        Format(Now, "yyyy-mm-dd hh-mm-ss") & ".docx"




    If .Version <= 12 Then
        .ActiveDocument.SaveAs SaveName
    Else
    .ActiveDocument.SaveAs2 SaveName
    End If


    .ActiveDocument.Close
    .Quit


    End With


    Set wdApp = Nothing
End Sub
```

Thank you in advance !!!

Tomasz


----------



## Sektor (Nov 21, 2016)

```
Dim rng As Range
Set rng = Range("A1:A3")
....
.Documents.Add rng(1) 'A1
'.Documents.Add rng(2) 'A2
'.Documents.Add rng(3) 'A3
```


----------



## beczer (Nov 21, 2016)

Hi Sektor, thanks for quick reply. Unfortunately it doesn't work. I think I did something wrong. Could you pls take a look ?

Sub CreateBasicWordReport()



```
Dim wdApp As Word.Application
    Dim SaveName As String
    Dim FileExt As String
    Dim rng As Range
    Set rng = Range("A1:A3")
    Set wdApp = CreateObject("Word.Application")


    With wdApp
        '.Visible = True
        '.Activate
        
        .Documents.Add rng(1) 'A1
        .Documents.Add rng(2) 'A2
        .Documents.Add rng(3) 'A3
```


----------



## Sektor (Nov 21, 2016)

Try *.Documents.**Open*


----------



## beczer (Nov 21, 2016)

The same


----------



## Sektor (Nov 21, 2016)

Oh, uncomment lines:

```
[COLOR=#333333]'.Visible = True[/COLOR]
[COLOR=#333333]'.Activate[/COLOR]
```


----------



## beczer (Nov 21, 2016)

Sektor, I'm really gratefull for your support but it still doesn't work (


----------



## Sektor (Nov 21, 2016)

I am sorry for not carefully reading your post. You're talking about _templates_ rather _documents_. Templates have extensions DOTX (macro-free) and DOTM (with macro) and DOT (for Word < 2007). As I see, you have DOCX file extension - which is *not* template but rather ordinary document.


----------



## beczer (Nov 21, 2016)

Yes I know but it is not a problem. I changed it before so it is fine. Anyway it still doesn't work  

VBA error -> .Documents.Add rng(1) 'A1


----------



## Macropod (Nov 21, 2016)

beczer: there are numerous problem with your code, but I guess you knew that already.

One thing that isn't clear is why you're using the Documents.Add method for an existing document instead of using it for a template or, alternatively, why you're not using the Documents.Open method for the existing document.

Another oddity is your retention of the .docx extension in the middle of the output filenames - for both the document and the pdf.

You also refer to saving the outputs to a folder created by VBA, which is quite possible, but you given no indication of how that folder's name might be determined.

Try the following code. It generates output files from your data in A1-A3.

```
Sub CreateWordOutputs()
Dim wdApp As Word.Application, wdDoc As Word.Document
Dim xlWkSht As Worksheet, StrName As String, i As Long
'Define our worksheet
Set xlWkSht = ActiveSheet
'Initialize Word
Set wdApp = CreateObject("Word.Application")
With wdApp
  'Loop through A1-A3 for our filenames
  For i = 1 To 3
    StrName = xlWkSht.Range("A" & i).Value
    'Open the file
    Set wdDoc = .Documents.Open(StrName)
    'Reconfigue the filename for output usage
    StrName = Split(StrName, .docx)(0) & " " & Format(Now, "yyyy-mm-dd hh-mm-ss")
    'Get our data
    xlWkSht.Range("A1", Range("A1").End(xlDown).End(xlToRight)).Copy
    With wdDoc
      'Add the data to our document
      .Bookmarks("bookmark1").Range.Paste
      'Save our document as both a Word document and as a PDF
      .SaveAs Filename:=StrName & ".docx", FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
      .SaveAs Filename:=StrName & ".pdf", FileFormat:=wdFormatPDF, AddToRecentFiles:=False
      'Close our file without re-saving
      .Close False
    End With
  Next
  'Exit Word
  .Quit
End With
'Cleanup
Set wdDoc = Nothing: Set wdApp = Nothing: Set xlWkSht = Nothing
End Sub
```


----------



## beczer (Nov 21, 2016)

Hi there

I am not advanced Vba programmer and I need your help. Could please review my code and tell how to change the DOC(template) file path ? In other words, I would like to use 3 different word templates so I can't put file path in VBA code as it is. I need to put a reference to cell where there is a file path.
A1 - C:\Users\Tom\Desktop\doc1.docx
A2 - C:\Users\Tom\Desktop\doc2.docx
A3 - C:\Users\Tom\Desktop\doc1.docx

Another thing, I would also like to add a possiblity to save DOCs and PDFs in created folder by VBA. 

My current VBA code:


```
Sub CreateWordTemplate()




    Dim wdApp As Word.Application
    Dim SaveName As String
    Dim FileExt As String
    Set wdApp = CreateObject("Word.Application")


    With wdApp
        '.Visible = True
        '.Activate
        
        .Documents.Add "C:\Users\name\Desktop\doc1.docx"




    Range("A1", Range("A1").End(xlDown).End(xlToRight)).Copy
        
    
    .Selection.GoTo What:=-1, Name:="bookmark1"
    .Selection.PasteSpecial


FileExt = ".pdf"
                            
                 SaveName = Environ("UserProfile") & "\Desktop\doc1.docx " & _
        Format(Now, "yyyy-mm-dd hh-mm-ss") & ".pdf"




                .ActiveDocument.ExportAsFixedFormat OutputFileName:=SaveName, ExportFormat:=17
              
        
       SaveName = Environ("UserProfile") & "\Desktop\doc1.docx " & _
        Format(Now, "yyyy-mm-dd hh-mm-ss") & ".docx"




    If .Version <= 12 Then
        .ActiveDocument.SaveAs SaveName
    Else
    .ActiveDocument.SaveAs2 SaveName
    End If


    .ActiveDocument.Close
    .Quit


    End With


    Set wdApp = Nothing
End Sub
```

Thank you in advance !!!

Tomasz


----------



## beczer (Nov 21, 2016)

Hi Macropod

Thanks for your support. Should I change something in above code ? I'm asking because it doesn't work 

Regarding saving the outputs to a folder created by VBA, I would also like to create a folder based on text in cell e.g C1 = Reports 22/11/2016. - folder name

Thanks 

Tomasz


----------



## Macropod (Nov 21, 2016)

beczer said:


> I'm asking because it doesn't work


If you want help with something, you're going to have to be far more descriotive than that! Precisely _what _doesn't work? In _what way _doesn't it work? What _error messages_, if any, do you get? What _data_ are in cells A1-A3 on the active sheet?

As for the folder creation, you cannot use anything like 'Reports 22/11/2016' (which you've indicated to be in C1), because a date in that format cannot be used for a folder name.


----------



## beczer (Nov 21, 2016)

Ok, sorry Macropod. You are right. 

Error: compile error: method or data member not found  / first line of code - highlighted 

Regarding Folder Creation, that's right. So let's say C1=text, without date.

Thanks once again!


----------



## Macropod (Nov 21, 2016)

beczer said:


> Error: compile error: method or data member not found  / first line of code - highlighted


The first code line cannot produce that error - not even if you hadn't set a reference to the Word library!
I did, however, pick up such an error further down. Change:
StrName = Split(StrName, .docx)(0) & " " & Format(Now, "yyyy-mm-dd hh-mm-ss")
to:
StrName = Split(StrName, ".docx")(0) & " " & Format(Now, "yyyy-mm-dd hh-mm-ss")


beczer said:


> Regarding Folder Creation, that's right. So let's say C1=text, without date.


And where is that folder to be created? Your cell contents don't mention the drive or anything else about the path to that folder. Neither do you mention anything about how or whether that new folder might be used in the code. At a fairly basic level, you could use code like:

```
On Error Resume Next
MkDir (StrPth & xlWkSht.Range("C3").Value)
On Error GoTo 0
```
or, with a bit more finesse:

```
If Dir(StrPth & xlWkSht.Range("C3").Value, vbDirectory) = "" Then MkDir StrPth & xlWkSht.Range("C3").Value
```
where StrPth holds the path (including the final "") to wherever the folder name in C3 is to be created.


----------



## beczer (Nov 22, 2016)

Macropod THANK YOU ! 

It works quite good now. There are just 3 things I would like to change and ask you to help with this:


1. After creating sucessfully DOC&PDF there is an error -> Run-time error "9" Subscript out of range 
Highlited: StrName = Split(StrName, ".docx")(0) & " " & Format(Now, "yyyy-mm-dd hh-mm-ss")


2. I can select template path from cell A1-A3 and it works perfect but I would like to change the name of generated files (now it is the same as template name + date). So Is it possible to use template from path in cell A1-A3 and assign new name to DOC&PDF file form different cell e.g B1 ?


3. The last question. How can I save generated files DOC&PDF directly in generated Folder from cell C3 


Thank you in advance for Your patience and support.


----------



## Macropod (Nov 22, 2016)

beczer said:


> After creating sucessfully DOC&PDF there is an error -> Run-time error "9" Subscript out of range
> Highlited: StrName = Split(StrName, ".docx")(0) & " " & Format(Now, "yyyy-mm-dd hh-mm-ss")


That would be because one or more cells in the A1-A3 range is empty. You said all three would have data, so I didn't bother with error-checking code.



beczer said:


> I can select template path from cell A1-A3 and it works perfect but I would like to change the name of generated files (now it is the same as template name + date). So Is it possible to use template from path in cell A1-A3 and assign new name to DOC&PDF file form different cell e.g B1 ?


Of course you can. The only reason the original name was included was because that's what you specified. BTW, you are not working with _templates_; you're working with _documents_. You should learn to name things correctly. Doing otherwise leads to confusion.


beczer said:


> The last question. How can I save generated files DOC&PDF directly in generated Folder from cell C3


By specifying that as the filepath. You still haven't said what the rest of that path is, though.


----------

