Compare Word documents without tracking formatting changes - vba

I have written a VBA routine for comparing docx files and saving the delta. I need to deactivate TrackFormatting in the delta but adding .trackFormatting = False does not do anything. In the compare method the CompareFormatting is false as well! How should I do this?
Sub ProduceDeltas()
Dim strFolderA As String
Dim strFolderB As String
Dim strFolderC As String
Dim strFileSpec As String
Dim strFileName As String
Dim objDocA As Word.Document
Dim objDocB As Word.Document
Dim objDocC As Word.Document
Dim dc As Word.Document
Dim FldrPickerInputA As FileDialog
Dim FldrPickerInputB As FileDialog
Dim FldrPickerOutput As FileDialog
Application.ScreenUpdating = False
Set FldrPickerInputA = Application.FileDialog(msoFileDialogFolderPicker)
Set FldrPickerInputB = Application.FileDialog(msoFileDialogFolderPicker)
Set FldrPickerOutput = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPickerInputA
.Title = "Choose first file: "
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
strFolderA = .SelectedItems(1) & "\"
End With
With FldrPickerInputB
.Title = "Choose second file: "
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
strFolderB = .SelectedItems(1) & "\"
End With
With FldrPickerOutput
.Title = "Choose output file: "
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
strFolderC = .SelectedItems(1) & "\"
End With
NextCode:
strFolderA = strFolderA
strFolderB = strFolderB
strFolderC = strFolderC
If strFolderA = "" Then GoTo ResetSettings
strFileSpec = "*.docx"
strFileName = Dir(strFolderA & strFileSpec)
Do While strFileName <> vbNullString
Set objDocA = Documents.Open(strFolderA & strFileName)
Set objDocB = Documents.Open(strFolderB & strFileName)
If objDocA.TablesOfContents.Count = 1 Then _
objDocA.TablesOfContents(1).Update
If objDocB.TablesOfContents.Count = 1 Then _
objDocB.TablesOfContents(1).Update
Set dc = Application.CompareDocuments(objDocA, objDocB, wdCompareDestinationNew, _
Granularity:=wdGranularityWordLevel, _
CompareFormatting:=False, RevisedAuthor:="IQTIG", CompareFootnotes:=False, CompareHeaders:=False)
dc.TrackFormatting = False
objDocA.Save
objDocB.Save
objDocA.Close
objDocB.Close
If dc.TablesOfContents.Count = 1 Then _
dc.TablesOfContents(1).Update
dc.SaveAs strFolderC & strFileName
dc.Close SaveChanges:=False
strFileName = Dir
Loop
Set objDocA = Nothing
Set objDocB = Nothing
ResetSettings:
Application.ScreenUpdating = True
End Sub

Which version of Word? On Word 2013, CompareFormatting:=False works for me.
One option is to accept (or reject) all formatting revisions after running the comparison. Before dc.SaveAs, insert the following:
dim oRevision as Revision
For Each oRevision In dc.StoryRanges(wdMainTextStory).Revisions
If (oRevision.Type<> wdRevisionInsert) and (oRevision.type <> wdRevisionDelete) then
oRevision.Accept ' or .Reject
End If
Next oRevision
(code modified from ExtractTrackedChangesToNewDoc by Lene Fredborg, supplied as-is with no warranty.)

Related

VBA Using FileDialog as Folder Path in a Loop

I am trying to make a copy of a workbook that I have, based on list of IDs. I have got this to work OK if I hard code the path, however I can't figure out how to do this where specifying the path using msoFileDialogFolderPicker.
I have tried a number of variations depending on what I have found online and have got as far as below but stuck. Help appreciated.
Dim xFilepath As Variant
Dim xFilename As String
xFilepath = Application.FileDialog(msoFileDialogFolderPicker)
xFilename = Range("Table9[ProgramID]") & " Product Financial Allocation" & ".xlsb"
With xFilepath
.Title = "Choose Destination"
.SHOW
mypath = .SelectedItems(1) & "\"
End With
mypath = mypath
Sheets("FILES").Range("A3").Select
For i = 1 To 3
Sheets("FILES").Range("A" & i).copy Sheets("TEMPLATE").Range("Table9[ProgramID]")
ActiveWorkbook.SaveCopyAs Filename:=mypath & Filename
FileFormat = 50
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
Workbooks.Open Filename:=mypath & Filename
Call DeleteQueries
ActiveWorkbook.Save
ActiveWorkbook.Close
Next i
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub
You can use the following code can be used to select folder and then you can append the folder path with file name.
Sub ChooseFolder()
Dim sFolder As String
' Open the select folder prompt
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a Folder"
If .Show = -1 Then ' if OK is pressed
sFolder = .SelectedItems(1)
End If
End With
Filename = "Test.xlsx"
Filepath = sFolder + "\" + Filename
If sFolder <> "" Then ' if a file was chosen
MsgBox Filepath 'Use this for further processing
End If
End Sub
Following code can be used select single file.
Private Sub ChooseFile()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel File", "*.xlsx"
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
MsgBox txtFileName
End Sub

How to import selected presentations from a folder?

How can I import a selected presentation from a particular folder?
Below are the code which I tried but it is importing all the presentations which are stored in a particular folder.
Sub Merge()
' After doing the merge, open presentation #1
' Then run this code:
Dim sPath As String
Dim cFileNames As New Collection
Dim sTemp As String
Dim x As Long
sPath = CurDir ' by default
If Right$(sPath, 1) <> "\" Then sPath = sPath & "\"
sPath = InputBox("Path to PPT files (ex: c:\my documents\", _
"Where are the files?", sPath)
If sPath = "" Then
Exit Sub
End If
sTemp = Dir(sPath & "*.pptx")
While sTemp <> ""
With cFileNames
.Add (sPath & sTemp)
End With
sTemp = Dir
Wend
If cFileNames.Count > 1 Then
' open the first file
Presentations.Open (cFileNames(1))
' Insert the other files
For x = 2 To cFileNames.Count
Call ActivePresentation.Slides.InsertFromFile( _
cFileNames(x), _
ActivePresentation.Slides.Count)
Next
End If
End Sub
For example. I have 10 presentations in XYZ folder but want to import only four selected presentations.
This should do it:
Sub Merge()
Dim sPath As String
Dim dlgOpen As FileDialog
Dim x As Integer
Dim vrtSelectedItem As Variant
'Set path to current dirrectory
sPath = CurDir
If Right$(sPath, 1) <> "\" Then sPath = sPath & "\"
'Set File Picker dialog
Set dlgOpen = Application.FileDialog(Type:=msoFileDialogFilePicker)
'Set initial path and view, set multiselect capability
With dlgOpen
.InitialFileName = sPath
.InitialView = msoFileDialogViewList
.AllowMultiSelect = True
'If user click on OK, insert selected files after last slide of current presentation
If .Show = -1 And .SelectedItems.Count > 0 Then
For x = 1 To .SelectedItems.Count
ActivePresentation.Slides.InsertFromFile .SelectedItems(x), ActivePresentation.Slides.Count
Next
Else
'User Cancelled
End If
End With
End Sub

Unicode UTF-8 at VBA

I have this VBA code to convert CSV to XLSX, which seems to work but output Excel have strange strings like "Aço" and "plástico" instead of "Aço" or "plástico". I think solution is to include "Unicode UTF-8", but I couldn't find a way. Any help would be appreciated.
Sub CSVtoXLSX()
Dim xFd As FileDialog
Dim xSPath As String
Dim xCSVFile As String
Dim xWsheet As String
Application.DisplayAlerts = False
Application.StatusBar = True
xWsheet = ActiveWorkbook.Name
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
xFd.Title = "Select a folder:"
If xFd.Show = -1 Then
xSPath = xFd.SelectedItems(1)
Else
Exit Sub
End If
If Right(xSPath, 1) <> "\" Then xSPath = xSPath + "\"
xCSVFile = Dir(xSPath & "*.csv")
Do While xCSVFile <> ""
Application.StatusBar = "Converting: " & xCSVFile
Workbooks.Open Filename:=xSPath & xCSVFile
ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xlsx", vbTextCompare), xlWorkbookDefault
ActiveWorkbook.Close
Windows(xWsheet).Activate
xCSVFile = Dir
Loop
Application.StatusBar = False
Application.DisplayAlerts = True
End Sub

Saving a File in Desired Folder Through Browsing With VBA

Writing a code to save a file with a defined filename to a specific folder entered by the user. However the file is being saved in a location previous to the specified location. For example I provide file save path as "C:\Users\arorapr\Documents\PAT" but the file is saving it in the path "C:\Users\arorapr\Documents". I have written the below code.
File_Name = Format(Now(), "DDMMYYYY") & "_" & LName & EmpIN & "_" & Range("C6").Value & "_" & Range("J3").Value & "_" & "PAT"
Application.DisplayAlerts = False
MsgBox "Please select the folder to save PAT"
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
End With
ActiveWorkbook.saveas Filename:=File_Name & ".xlsm", FileFormat:=52
Application.DisplayAlerts = True
ActiveWorkbook.Close
Your challenge is that you're opening a file dialog, but not using the user's choice from that in the saveas. Try something along these lines:
Sub SaveFile()
Dim FolderName As String
File_Name = Format(Now(), "DDMMYYYY") & "_" & LName & EmpIN & "_" & Range("C6").Value & "_" & Range("J3").Value & "_" & "PAT"
Application.DisplayAlerts = False
MsgBox "Please select the folder to save PAT"
' Pop up the folder-selection box to get the folder form the user:
FolderName = GetFolder()
' If the user didn't select anything, you can't save, so tell them so:
If FolderName = "" Then
MsgBox "No folder was selected. Program will terminate."
Exit Sub
End If
' Create a path by combining the file and folder names:
File_Name = FolderName & "\" & File_Name & ".xlsm"
ActiveWorkbook.SaveAs Filename:=File_Name, FileFormat:=52
Application.DisplayAlerts = True
ActiveWorkbook.Close
End Sub
' A separate function to get the folder name and return it as a string
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Hope that helps.
In your code, you are not saving the path of the selected folder to a variable. In the code below, the path is saved to the variable selectedFolder, which gets its value from fldr.SelectedItems(1). Then the path + "\" + YourFileName & .xlsm is saved:
Option Explicit
Sub TestMe()
Dim fldr As FileDialog
Dim selectedFolder As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.Show
selectedFolder = .SelectedItems(1)
End With
ActiveWorkbook.SaveAs Filename:=selectedFolder & "\" & "YourFileName" & ".xlsm"
End Sub
Or alternatively, you may use a function, returning the folder's path from here:
VBA - Folder Picker - set where to start
A robust funciton, that I am using to GetFolder is this one:
Option Explicit
Sub myPathForFolder()
Debug.Print GetFolder(Environ("USERPROFILE"))
End Sub
Function GetFolder(Optional InitialLocation As String) As String
On Error GoTo GetFolder_Error
Dim FolderDialog As FileDialog
Dim SelectedFolder As String
If Len(InitialLocation) = 0 Then InitialLocation = ThisWorkbook.Path
Set FolderDialog = Excel.Application.FileDialog(msoFileDialogFolderPicker)
With FolderDialog
.Title = "My Title For Dialog"
.AllowMultiSelect = False
.InitialFileName = InitialLocation
If .Show <> -1 Then GoTo GetFolder_Error
SelectedFolder = .SelectedItems(1)
End With
GetFolder = SelectedFolder
On Error GoTo 0
Exit Function
GetFolder_Error:
Debug.Print "Error " & Err.Number & " (" & Err.Description & ")
End Function

How to export images from word doc to local drive

I wanted to export the images on the word doc to local drive how can I do it from excel using vba.
Sub gen_Files()
Dim WdApp As Word.Application, Doc As Word.Document, fPath As String
Dim i As Long
fPath = ThisWorkbook.Path & Application.PathSeparator & "Test.docx"
If fPath = "" Or Dir(fPath) = "" Then MsgBox "Invalid file path.": Exit Sub
Set WdApp = New Word.Application
WdApp.Visible = True
Set Doc = WdApp.Documents.Open(fPath)
Doc.SaveAs2 ThisWorkbook.Path & "\New.docx", FileFormat:=12
For i = 1 To Doc.InlineShapes.Count
'Doc.InlineShapes(i).Range.ExportAsFixedFormat(ThisWorkbook.Path & Application.PathSeparator & i & ".jpg",wdExportFormatXPS,False,,,,,,,,,,)
Next i
'Save the file and done
Doc.Save
Doc.Close
WdApp.Quit
End Sub
The code would be like this.
Sub gen_Files()
Dim WdApp As Word.Application, Doc As Word.Document, fPath As String
Dim i As Long
Dim cht As Chart, obj As ChartObject
Dim Ws As Worksheet
Dim myFn As String
Dim shp As InlineShape
Set Ws = ActiveSheet
fPath = ThisWorkbook.Path & Application.PathSeparator & "Test.docx"
If fPath = "" Or Dir(fPath) = "" Then MsgBox "Invalid file path.": Exit Sub
Set WdApp = New Word.Application
WdApp.Visible = True
Set Doc = WdApp.Documents.Open(fPath)
Doc.SaveAs2 ThisWorkbook.Path & "\New.docx", FileFormat:=12
For i = 1 To Doc.InlineShapes.Count
Set shp = Doc.InlineShapes(i)
shp.Range.CopyAsPicture
Set obj = Ws.ChartObjects.Add(Range("i1").Left, 0, shp.Width, shp.Height)
myFn = ThisWorkbook.Path & Application.PathSeparator & i & ".jpg"
With obj.Chart
.Paste
.Export myFn
End With
obj.Delete
Next i
'Save the file and done
Doc.Save
Doc.Close
WdApp.Quit
End Sub