I am using an excel vba project to create an word file then saving it to pdf using following code.
wordapp.ActiveDocument.SaveAs2 "" & folder & "" & pdfname & ".pdf", 17
I want to print the same word file using PDF printer at path of
& folder &
and filename as
& pdfname &
I have tried using this as a macro in word file but it asks for a path and filename. Does not automate it.
Probably the easiest way is to use the pdfName as a string and to put a \ sign before it and the folder.
Try to run this code from Excel file, just make sure that the Excel file is saved successfully, otherwise ThisWorkbook.Path would be equl to empty string and you will be asked to save the file during runtime -> If ThisWorkbook.Path = vbNullString Then ThisWorkbook.Save
Public Sub TetMe()
Dim wordApp As Object
Dim WordDoc As Object
Dim folder As String
Dim pdfName As String: pdfName = "someName"
If ThisWorkbook.Path = vbNullString Then ThisWorkbook.Save
Set wordApp = CreateObject("Word.Application")
Set WordDoc = wordApp.documents.Add
folder = ThisWorkbook.Path & "\"
wordApp.ActiveDocument.SaveAs2 folder & pdfName & ".pdf", 17
End Sub
If you are wondering what 17 after .SaveAs2 is, it is wdSaveFormat Enumeration for wdFormatPDF.
WdSaveFormat Enumeration MSDN
Following Code can be used to make Foxit PDF Printer run for your code.
MAIN CODE
ActivePrinter = "Foxit Reader PDF Printer"
printoutcommand = "wordapp.ActiveDocument.PrintOut
Range:=wdPrintAllDocument, PrintToFile:=True,OutputFilename:=" & sItem &
pdfname & "_temp" & ".pdf"
wordapp.Application.Run "FoxitPrint2PDF"
Application.Wait (Now + TimeValue("0:00:02"))
Name "C:\Users\shena\Documents\Document1.pdf" As pdfname & "_temp" & ".pdf"
Application.Wait (Now + TimeValue("0:00:02"))
FileCopy "C:\Users\shena\Documents\" & pdfname & "_temp" & ".pdf", sItem & "" & pdfname & "_temp" & ".pdf"
Application.Wait (Now + TimeValue("0:00:02"))
Kill "C:\Users\shena\Documents\" & pdfname & "_temp" & ".pdf"
Application.Wait (Now + TimeValue("0:00:02"))
wordapp.activedocument.Close SaveChanges:=wdDoNotSaveChanges
wordapp.Quit
Set wordapp = Nothing
FoxitPrint2PDF is macro used to set Foxit PDF Printer as default printer and then reset it. Code is as follows
Dim sCurrentPrinter As String
On Cancel GoTo Cancelled:
sCurrentPrinter = ActivePrinter
ActivePrinter = "Foxit Reader PDF Printer"
Application.PrintOut FileName:=""
Cancelled:
ActivePrinter = sCurrentPrinter
Its just an idea given same code can be written in a module where print operation is going on.
In main code some cut paste operations are seen. Here is the explanation of the same. When we select PDF as a printer we have selected a default location for converted PDF. from that location we are taking it to our desired location. You can see those option at right click on "Foxit Reader PDF Printer" then click on Printing Preferences. Screen shot of the same is given below for reference.
Highlighted options are important for us.
Related
I would like to know if the SaveAs window filename textbox has a property that I could set text to. Currently I'm using the sendkeys function, which works fine for most things until I run into the special characters like parentheses.
My current code is basically:
SaveFldr = "S:\Desktop\grape
Filename = "Grape Data"
Application.SendKeys "{F12}" ' opens the save as window
Application.SendKeys SaveFldr & Filename & ".pdf"
Application.SendKeys "{Enter}"
Basically I'm looking for a way to set the filename without the sendkeys function. Such as..
Filename.Textbox = Filename
** Assuming the textbox within the SaveAs window was named that.
You could use code like the following one
Sub CallSaveAs()
Dim fileSaveName As Variant
Dim SaveFldr As String
Dim fileName As String
SaveFldr = "S:\Desktop\grape"
fileName = "Grape Data"
fileSaveName = Application.GetSaveAsFilename( _
fileFilter:="PDF Files (*.PDF), *.pdf", _
InitialFileName:=SaveFldr & Application.PathSeparator & fileName)
If Not TypeName(fileSaveName) = "Boolean" Then
MsgBox "Save as " & fileSaveName
' Save the sheetas PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fileName
End If
End Sub
End Sub
I want to open a PDF file and print the subaddress that i specified, but when i use Application.SendKeys "(%{1068})" just print screen Userform. My issue is how print screen just subaddress Rating Changes.
enter code here
Private Sub AlteraRating_Click()
Dim strFolde As String, Month As String, Year As String, strFile As String
Month = Format(SalvaData, "mm")
Year = Format(SalvaData, "yyyy")
pdfData = Format(SalvaData, "yyyymmdd")
strFolder = "C:\Report\Report of Investments\" & Year & "\" & Month & "\"
strFile = strFolder & "RAI_INFRAPREV PLANO CV_F03148_" & pdfData & ".pdf"
ThisWorkbook.FollowHyperlink strFile, "Rating Changes"
Application.SendKeys "(%{1068})"
DoEvents
End Sub
Try using the following code in order to open the PDF, FollowHyperlink won't keep it open long enough to print screen.
Dim shell As Object
Set shell = CreateObject("WScript.Shell")
shell.Run Chr(34) & strFile & Chr(34), 1, False
I'm looking for a code to zip the folders of a path specified in my cells(1,1).value
After googling i found vba codes to zip the files of a folder but they are using WinZip.
My office machine does not have a WinZip installed and we are restricted to use WinZip. Could anyone please help with this. I need to use the default zip (Right click -> Send to compressed ZIP folder)
Thanks!
Sub Zip_File_Or_Files()
Dim strDate As String, DefPath As String, sFName As String
Dim oApp As Object, iCtr As Long, I As Integer
Dim FName, vArr, FileNameZip
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
strDate = Format(Now, " dd-mmm-yy h-mm-ss")
FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"
'Browse to the file(s), use the Ctrl key to select more files
FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
MultiSelect:=True, Title:="Select the files you want to zip")
If IsArray(FName) = False Then
'do nothing
Else
'Create empty Zip File
NewZip (FileNameZip)
Set oApp = CreateObject("Shell.Application")
I = 0
For iCtr = LBound(FName) To UBound(FName)
vArr = Split97(FName(iCtr), "\")
sFName = vArr(UBound(vArr))
If bIsBookOpen(sFName) Then
MsgBox "You can't zip a file that is open!" & vbLf & _
"Please close it and try again: " & FName(iCtr)
Else
'Copy the file to the compressed folder
I = I + 1
oApp.Namespace(FileNameZip).CopyHere FName(iCtr)
'Keep script waiting until Compressing is done
On Error Resume Next
Do Until oApp.Namespace(FileNameZip).items.Count = I
Application.Wait (Now + TimeValue("0:00:01"))
Loop
On Error GoTo 0
End If
Next iCtr
MsgBox "You find the zipfile here: " & FileNameZip
End If
End Sub
Powered by Ron De Bruin - http://www.rondebruin.nl/win/s7/win001.htm
I have found it helpful to make a couple of tweaks to make this more friendly for the user (which for this sort of thing is often myself).
Limit how long you're willing to wait for the file & message the user if that time limit was reached without success
Add a DoEvents so that you can ctrl+break to pause the code in case you want to inspect (otherwise - can sometimes have to crash Excel, in my experience)
Add a statusbar update so the user knows what's going on
Sub ZipTheFile(ByVal strPath As String, ByVal strFileNameXls As String, ByVal strFileNameZip As String)
'Taken largely from Ron De Bruin - https://www.rondebruin.nl/win/s7/win001.htm
'Create empty Zip File
NewZip (strPath & strFileNameZip)
'Copy the file in the compressed folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(strPath & strFileNameZip).CopyHere strPath & strFileNameXls
'Keep script waiting until Compressing is done (OR we waited more than 40 seconds...)
On Error Resume Next
i = 0
Do Until oApp.Namespace(strPath & strFileNameZip).Items.Count = 1 Or i > 40 '<-- set how long you're willing to wait here
Application.Wait (Now + TimeValue("0:00:01"))
DoEvents
Application.StatusBar = "Waiting for Zip - counter: " & i
i = i + 1
Loop
On Error GoTo 0
If i > 40 Then MsgBox "there seems to have been a problem putting the file into the zip foder. Check the zip at: " & strPath & strFileNameZip
End Sub
Sub NewZip(sPath) 'You need this sub-routine as well
'Create empty Zip File
'by Ron De Bruin - https://www.rondebruin.nl/win/s7/win001.htm
'Changed by keepITcool Dec-12-2005
If Len(Dir(sPath)) > 0 Then Kill sPath
Open sPath For Output As #1
Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
Close #1
End Sub
STILL Powered by Ron De Bruin - http://www.rondebruin.nl/win/s7/win001.htm
I am running below code but unable to save opened notepad file in same format, code is below
Dim mytxtfile
Dim flname, flname2 As String
flname = Dir(ThisWorkbook.path & "\" & "myfile.csv")
flname2 = ThisWorkbook.path & "\" & "myfile_1.txt"
mytxtfile = Shell("C:\WINDOWS\notepad.exe " & ThisWorkbook.path & "\" & flname, 1)
AppActivate mytxtfile
SendKeys "%(FAX)", True
Application.Wait TimeSerial(Hour(Now()), Minute(Now()), Second(Now()) + 2)
SendKeys "%S", True '
"Save as" dialog box opens here, but now I want to give the file name which is in flname2 i.e (myfile_1.txt) and then save and close notepad.
Copy the file using the File System Object:
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CopyFile ThisWorkbook.path & "\" & "myfile.csv", ThisWorkbook.path & "\" & "myfile_1.txt"
I use a VBA script (see below) in Word 2013 to convert a folder of .rtf files to .docx files. It mostly works, but has two minor problems.
I have to acknowledge that each original file is an .rtf file. When Word opens each .rtf file there's a dialog that requires me to confirm that each file is an .rtf file.
When I view converted .docx files in Word there's a "compatibility mode" header, which suggests that I haven't properly converted.
Are there any fixes for these problems? The first one kind of undermines the whole point of scripting and I'm afraid the second one will cause unforeseen problems.
Sub ConvertRtfToDocx()
Set oWord = CreateObject("Word.Application")
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select folder..."
.Show
myFolder = .SelectedItems.Item(1)
End With
myWildCard = InputBox(prompt:="Enter wild card...")
myDocs = Dir(myFolder & "\" & myWildCard)
While myDocs <> ""
Debug.Print myDocs
Set oDoc = oWord.Documents.Open(myFolder & "\" & myDocs)
oDoc.SaveAs myFolder & "\" & Left(myDocs, Len(myDocs) - 4) & ".docx", _
wdFormatXMLDocument
myDocs = Dir()
Wend
oWord.Quit
End Sub
The following code works.
Sub ConvertRtfToDocx()
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select folder..."
.Show
myFolder = .SelectedItems.Item(1)
End With
myWildCard = InputBox(prompt:="Enter wild card...")
myDocs = Dir(myFolder & "\" & myWildCard)
While myDocs <> ""
Documents.Open FileName:=myFolder & "\" & myDocs, ConfirmConversions:=False
ActiveDocument.SaveAs2 FileName:=myFolder & "\" & Left(myDocs, Len(myDocs) - 4) & ".docx", _
FileFormat:=wdFormatDocumentDefault, _
CompatibilityMode:=wdCurrent
ActiveDocument.Close SaveChanges:=False
myDocs = Dir()
Wend
End Sub
I did some restructuring (e.g., use ActiveDocument instead of creating my own object), but the real changes that did it were to
set ConfirmConversions:=False on open
use the SaveAs2 method and set FileFormat:=wdFormatDocumentDefault and CompatibilityMode:=wdCurrent
I guess that both of these can be set as default (I'm overwhelmed by Office options and leave the defaults).