PDA

View Full Version : [SOLVED:] Word 2003 - Help needed with a compare documents macro



rodrigobele
02-05-2016, 01:14 PM
Dear Word VBA coders,

I have the following code which compares word documents from one folder with documents with the same filename in another folder, highlights eventual changes and saves them in another document in a 3rd folder.

I'm still an amateur coder. I can work the ifs and the for/while loops, but I'm far from getting acquainted with the majority of VBA commands and objects.

Is it possible to alter this macro so that it skips documents which doesn't have a corresponding one in the second folder (instead of terminating the macro execution with an error) and so that it only saves the documents which were actually changed in the 3rd folder?

I appreciate any help, even if you just point me to word documentation.

Cordially,
Rodrigo

Sub Compare_Docs()
cpath = "U:\TURMAS\10ATURMA\Rodrigo\Pasta1\"
inpath = "U:\TURMAS\10ATURMA\Rodrigo\Pasta2\"
outpath = "U:\TURMAS\10ATURMA\Rodrigo\Pasta3\"
fname = Dir(inpath & "*.jus")
Do While Len(fname) > 0
Set doc = Documents.Open(inpath & fname)
doc.Compare cpath & fname
doc.Merge inpath & fname
doc.SaveAs outpath & fname
doc.Close
fname = Dir
Loop
End Sub

gmayor
02-06-2016, 12:01 AM
You need to establish if the file you wish to compare exists, so the following will do that. Beyond that I haven't tested your code.

Get in to the habit of declaring your variables. You can set the VBA editor Tools > Options > Require Variable Declaration which will add Option Explicit to the modules you create thus forcing you to declare the variables.
Option Explicit
Sub Compare_Docs()
Dim doc As Document
Dim fName As String
Const cpath As String = "U:\TURMAS\10ATURMA\Rodrigo\Pasta1\"
Const inpath As String = "U:\TURMAS\10ATURMA\Rodrigo\Pasta2\"
Const outpath As String = "U:\TURMAS\10ATURMA\Rodrigo\Pasta3\"
fName = Dir(inpath & "*.jus")
Do While Len(fName) > 0
If FileExists(cpath & fName) Then
Set doc = Documents.Open(inpath & fName)
doc.Compare cpath & fName
doc.Merge inpath & fName
doc.SaveAs outpath & fName
doc.Close
End If
fName = Dir
Loop
lbl_Exit:
Set doc = Nothing
Exit Sub
End Sub

Private Function FileExists(strFullName As String) As Boolean
'Graham Mayor
'strFullName is the name with path of the file to check
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(strFullName) Then
FileExists = True
Else
FileExists = False
End If
lbl_Exit:
Exit Function
End Function

rodrigobele
02-11-2016, 11:34 AM
Thank you very much, gmayor! That was rignt on the spot. Lesson learned.