2013-05-08 6 views
1

Итак, у меня есть шаблон с поддержкой макросов Word 2010 с моими удобными формами денди, которые люди могут заполнить. Я создал кнопку, которая говорит «Преобразовать в PDF», потому что люди не знают, как это сделать изначально. Я ввел в редактор VB конкретного CommandButton, что хочу иметь эту функциональность. Вот что в этой кнопке:VB-скрипт для экспорта в pdf в Command Button (ActiveX) в Word 2010

Private Sub CommandButton1_Click() 
Sub Convert_PDF() 

Dim desktoploc As String 
Dim filename As String 
Dim mypath As String 

    desktoploc = CreateObject("WScript.Shell").SpecialFolders("Desktop") 
    filename = ThisDocument.Name 
    mypath = desktoploc & "\" & filename 

    ActiveDocument.ExportAsFixedFormat OutputFileName:= _ 
     mypath, _ 
     ExportFormat:=wdExportFormatPDF, OpenAfterExport:=True, OptimizeFor:= _ 
     wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _ 
     Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _ 
     CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _ 
     BitmapMissingFonts:=True, UseISO19005_1:=False 
End Sub 
End Sub 

Когда я запускаю код, я получаю ..... БАМ! Ошибка компиляции: Ожидаемая End Sub

Если я вынимаю Суб Convert_PDF() и его относящиеся End Sub, вдруг я не получаю сообщения об ошибках суб, но я получаю еще одно сообщение об ошибке:

The file [file name] cannot be opened beacause there are problems with the contents. Details: The file is corrupt and cannot be opened. Заменить [имя файла ] с фактическим именем моего файла.

Я буду полностью честным, я полный n00b в VB и Google, оказывается, что не очень полезно до сих пор:/

Любое понимание?

+0

Я думаю, вам нужно создать объект PDF. Когда я пытался сделать что-то подобное лет назад, у них не было свободных библиотек, чтобы помочь в этом. В качестве обходного пути (пока я не смогу увидеть, что я могу найти) вы можете печатать на PDF-принтер и иметь свой макро-вызов. – Jeff

+1

@Jeff - Excel 2010 имеет встроенный save-as-PDF: нет необходимости в дополнительных библиотеках ... –

+0

У вас есть два вложенных подсистемы - это недействительно VBA. –

ответ

2
Private Sub CommandButton1_Click() 
    Convert_PDF 
End Sub 


Sub Convert_PDF() 

Dim desktoploc As String 
Dim filename As String 
Dim mypath As String 

    desktoploc = CreateObject("WScript.Shell").SpecialFolders("Desktop") 
    filename = ThisDocument.Name 
    mypath = desktoploc & "\" & filename & ".pdf" 

    ActiveDocument.ExportAsFixedFormat OutputFileName:= _ 
     mypath, _ 
     ExportFormat:=wdExportFormatPDF, OpenAfterExport:=True, OptimizeFor:= _ 
     wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _ 
     Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _ 
     CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _ 
     BitmapMissingFonts:=True, UseISO19005_1:=False 
End Sub 
+0

попробуем это из Тима, и дайте знать – jparnell8839

+0

Работали красиво. Любой способ добавить месяц, который выбран из раскрывающегося поля формы? Например, у меня есть раскрывающийся список, где вы можете установить месяц ... в VBA для кнопки, я создал строку для пользователя, которая: пользователь = VBA.Environ ("USERNAME") I изменили строку mypath на: mypath = desktoploc & "\ Metrics \" & filename & "-" & date & "-" & user Теперь мне просто нужно выяснить, как подать информацию с помощью drop- вниз в строку Date:/ – jparnell8839

+0

Извините. Формы Word - это не то, с чем я знаком. –

0

Для вашего РАЗВЕЙТЕ вопрос:

Это зависит от того, как Вы выбираете дату. Если вы выбираете «Контроль содержимого даты», вам нужно будет следовать приведенному ниже коду. Если вы выбираете из комбинированного поля Active X, тогда вам нужно вытащить его значение [January] из раскрывающегося списка. msgbox(DropDown.Value) покажет "January. Вы можете поместить его в оператор if, если вам нужно преобразовать месяц в число [if DropDown.Value) = "January" Then...].

Код ниже для получения данных из «Дата Picker Content Control» в слове

'put this at the top of the code, outside any functions/subs 
Dim DateGlobal As Date 

'This sub will run whenever you exit any ContentControl function 
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean) 
If IsDate(ActiveDocument.SelectContentControlsByTitle("Date").Item(1).Range.Text) = True Then 
    DateGlobal = ActiveDocument.SelectContentControlsByTitle("Date").Item(1).Range.Text 
End If 

'Now use DateGlobal wherever you need it; it will be in date format. 
msgbox(DateGlobal)     'Shows date as default date format 
msgbox(myDateFormat(DateGlobal)  'Shows date as your custom date format (below) 
End Sub 

'************************************************************************************ 
'      Custom DATE format (instead of computer default) 
'      Found elsewhere on this site, I like my format yyyy/mm/dd 
'************************************************************************************ 

Function myDateFormat(myDate) 
    d = WhatEver(Day(myDate)) 
    M = WhatEver(Month(myDate)) 
    y = Year(myDate) 
    myDateFormat = y & "/" & M & "/" & d 
End Function 

Function WhatEver(num) 
    If (Len(num) = 1) Then 
     WhatEver = "0" & num 
    Else 
     WhatEver = num 
    End If 
End Function