简体   繁体   English

使用单词SaveAs FileFormat的VBA宏:= wdFormatPDF创建.docx

[英]VBA macro using word SaveAs FileFormat:=wdFormatPDF creates .docx

wordTemplate = "c:\someTemplate.docx"
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.documents.Add Template:=wordTemplate, NewTemplate:=False, DocumentType:=0

'''here I iterate and do stuffs, and then:'''


With objWord.ActiveDocument
    .SaveAs Filename:=("somePath" & "aName"), FileFormat:=wdFormatPDF
    .Close
End With
With objWord
    .Quit
End With

this is resulting in a .docx file. 这将产生一个.docx文件。 ¿shouldn't wdFormatPDF give me a PDF? ¿wdFormatPDF不能给我PDF吗?

EDIT: I modified the .SaveAs line to: 编辑:我将.SaveAs行修改为:

.SaveAs Filename:=(Hoja1.Range("N6").Text & Hoja1.Range("A1") & ".pdf"), FileFormat:=wdFormatPDF

and

.SaveAs2 Filename:=(Hoja1.Range("N6").Text & Hoja1.Range("A1") & ".pdf"), FileFormat:=wdFormatPDF

but both generate a .pdf file that cannot be rendered. 但两者都会生成无法呈现的.pdf文件。

What you get depends on what you're passing as "aName". 您得到什么取决于您作为“ aName”传递的内容。 If it includes a .docx extension , for example, your PDF will have an invalid .docx extension. 例如,如果它包含.docx扩展名,则您的PDF将具有无效的.docx扩展名。

It makes no difference whether you're using SaveAs or SaveAs2 for this. 无论您是使用SaveAs还是SaveAs2都没有关系。

you need to use the SaveAs2 method like this (tested ans it's working): 您需要像这样使用SaveAs2方法(已测试ans是否有效):

wordTemplate = "c:\someTemplate.docx"
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.documents.Add Template:=wordTemplate, NewTemplate:=False, DocumentType:=0

'''here I iterate and do stuffs, and then:'''


With objWord.ActiveDocument

    .SaveAs2 "C:\test\MyDoc.pdf", 17

    '.SaveAs Filename:=("c:\test\" & "test"), FileFormat:=wdFormatPDF
    .Close
End With
With objWord
    .Quit
End With

Well, my problem was related to the syntax: 好吧,我的问题与语法有关:

this didn't work: 这不起作用:

.SaveAs Filename:=(Hoja1.Range("N6").Text & Hoja1.Range("A1") & ".pdf"), FileFormat:=wdFormatPDF

while this did: 虽然这样做:

.SaveAs (Hoja1.Range("N6").Text & Hoja1.Range("A1") & ".pdf"), 17

The problem, then, was that after changing that, the 问题是,在改变了这一点之后,

.Close

in the next line asked me to save changes to original document (something that worked well before). 在下一行中,我要求将更改保存到原始文档中(以前效果很好)。 It forced me to explicitly discard the changes like this: 它迫使我明确放弃这样的更改:

.Close _
        SaveChanges:=wdDoNotSaveChanges

Final solution is: 最终解决方案是:

With objWord.ActiveDocument
    .SaveAs (Hoja1.Range("N6").Text & Hoja1.Range("A1") & ".pdf"), 17
    .Close _
        SaveChanges:=wdDoNotSaveChanges
End With

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM