I am trying to do find replace from excel to word using vba, but the problem is, in some of the word table it is keeping field blank.
After adjusting the table height in word it works but sometime it disturbs the other table and some time it paste as an image instead of text.
Below is the program which i have written for find and replace. Can anyone help me on below program. Thanks in advance.
Sub replication()
Application.EnableEvents = False
Application.ScreenUpdating = False
Dim wd As Word.Application
Dim wdDoc As Word.Document
Dim irow As Long
Dim i As Long
Dim k As Long
Dim sh As Worksheet
Set wd = New Word.Application
Set sh = ThisWorkbook.Sheets("Sheet1")
irow = 3
i = Application.WorksheetFunction.CountA(Sheet1.Range("A2:IZ2").Value)
Do While sh.Range("A" & irow).Value <> ""
Set wdDoc = wd.Documents.Open(ThisWorkbook.Path & "\Standard.docx")
wd.Visible = False
On Error Resume Next
wdDoc.SaveAs2 (ThisWorkbook.Path & "\Word\" & sh.Range("B" & irow).Value & ".docx")
For j = 2 To 3
With wdDoc.Content.Find
.Text = Sheet1.Cells(2, j)
.Replacement.Text = Sheet1.Cells(irow, j)
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
Next j
For k = 4 To i
With wdDoc.Content.Find
.Text = Sheet1.Cells(2, k)
If Len(Sheet1.Cells(irow, k)) > 120 Then
Sheet1.Cells(irow, k).Copy
'Selection.PasteExcelTable False, False, False
.Replacement.Text = "^c"
.Replacement.ClearFormatting
Else
.Replacement.Text = Sheet1.Cells(irow, k)
.Replacement.ClearFormatting
End If
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
Selection.ParagraphFormat.Alignment = wdAlignParagraphJustify
'.Range.ParagraphFormat.Alignment = 3
End With
Next k
Dim footr As Word.HeaderFooter
For Each footr In wdDoc.Sections(1).Footers
With footr.Range.Find
.Text = "<Scheme Name>"
.Replacement.Text = Sheet1.Cells(irow, 2)
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindStop
End With
Next footr
wd.Visible = False
Dim t As Table
'Windows(sh.Range("B" & irow).Value & ".docx").Activate
Documents(sh.Range("B" & irow).Value & ".docx").Activate
ActiveDocument.Range.Select
ActiveDocument.Range.Select
ActiveDocument.Range.Select
Documents(sh.Range("B" & irow).Value & ".docx").Activate
ActiveDocument.Range.Select
Selection.ParagraphFormat.Alignment = wdAlignParagraphJustify
wdDoc.ExportAsFixedFormat OutputFileName:= _
ThisWorkbook.Path & "\PDF\" & sh.Range("B" & irow).Value & ".pdf" _
, ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=138, _
Item:=wdExportDocumentWithMarkup, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
wdDoc.Close
Set wdDoc = Nothing
irow = irow + 1
Loop
wd.Quit
Set wd = Nothing
Application.EnableEvents = True
Application.ScreenUpdating = True
MsgBox "Replication done successfully!"
End Sub
Related
I am updating this post with update code.
Sub ImportWordTable()
Dim WordApp As Object
Dim WordDoc As Object
Dim arrFileList As Variant, FileName As Variant
Dim tableNo As Integer 'table number in Word
Dim tableStart As Integer
Dim tableTot As Integer
Dim LastRow As Long
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
'On Error Resume Next
arrFileList = Application.GetOpenFilename("Word files (.doc; .docx),.doc;.docx", 2, _
"Browse For file containing table To be imported", , True)
If Not IsArray(arrFileList) Then Exit Sub '(user cancelled import file browser)
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
'Range("A:AZ").ClearContents
For Each FileName In arrFileList
Set WordDoc = WordApp.Documents.Open(FileName, ReadOnly:=True)
With WordDoc
tableNo = WordDoc.tables.Count
tableTot = WordDoc.tables.Count
If tableNo = 0 Then
MsgBox WordDoc.Name & " contains no tables", vbExclamation, "Import Word Table"
ElseIf tableNo > 1 Then
tableNo = InputBox(WordDoc.Name & " contains " & tableNo & " tables." & vbCrLf & _
"Enter the table To start from", "Import Word Table", "1")
End If
' Set the header for the Colums
With .tables(tableNo)
Parent.Range("A" & LastRow).Value = .cell(1, 1).Range
Parent.Range("B" & LastRow).Value = .cell(2, 1).Range
Parent.Range("C" & LastRow).Value = .cell(3, 1).Range
Parent.Range("D" & LastRow).Value = .cell(4, 1).Range
Parent.Range("E" & LastRow).Value = .cell(5, 1).Range
Parent.Range("F" & LastRow).Value = .cell(6, 1).Range
Parent.Range("G" & LastRow).Value = .cell(7, 1).Range
Parent.Range("H" & LastRow).Value = .cell(8, 1).Range
Parent.Range("I" & LastRow).Value = .cell(9, 1).Range
Parent.Range("J" & LastRow).Value = .cell(10, 1).Range
Parent.Range("K" & LastRow).Value = .cell(11, 1).Range
Parent.Range("L" & LastRow).Value = .cell(12, 1).Range
Parent.Range("M" & LastRow).Value = .cell(13, 1).Range
Parent.Range("N" & LastRow).Value = .cell(14, 1).Range
Parent.Range("O" & LastRow).Value = .cell(15, 1).Range
Parent.Range("P" & LastRow).Value = .cell(16, 1).Range
Parent.Range("Q" & LastRow).Value = .cell(17, 1).Range
Parent.Range("R" & LastRow).Value = .cell(18, 1).Range
Parent.Range("S" & LastRow).Value = .cell(19, 1).Range
Parent.Range("T" & LastRow).Value = .cell(20, 1).Range
Parent.Range("U" & LastRow).Value = .cell(21, 1).Range
Parent.Range("V" & LastRow).Value = .cell(22, 1).Range
Parent.Range("W" & LastRow).Value = .cell(23, 1).Range
Parent.Range("X" & LastRow).Value = .cell(24, 1).Range
Parent.Range("Y" & LastRow).Value = .cell(25, 1).Range
End With
LastRow = LastRow + 1
' Get the date from the tables
For tableStart = tableNo To tableTot
With .tables(tableStart)
.cell(1, 2).Range.Copy
With Range("A" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(2, 2).Range.Copy
With Range("B" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(3, 2).Range.Copy
With Range("C" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(4, 2).Range.Copy
With Range("D" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(5, 2).Range.Copy
With Range("E" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(6, 2).Range.Copy
With Range("F" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(7, 2).Range.Copy
With Range("G" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(8, 2).Range.Copy
With Range("H" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(9, 2).Range.Copy
With Range("I" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(10, 2).Range.Copy
With Range("J" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(11, 2).Range.Copy
With Range("K" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(12, 2).Range.Copy
With Range("L" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(13, 2).Range.Copy
With Range("M" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(14, 2).Range.Copy
With Range("N" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(15, 2).Range.Copy
With Range("O" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(16, 2).Range.Copy
With Range("P" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(17, 2).Range.Copy
With Range("Q" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(18, 2).Range.Copy
With Range("R" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(19, 2).Range.Copy
With Range("S" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(20, 2).Range.Copy
With Range("T" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(21, 2).Range.Copy
With Range("U" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(22, 2).Range.Copy
With Range("V" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(23, 2).Range.Copy
With Range("W" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(24, 2).Range.Copy
With Range("X" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.cell(25, 2).Range.Copy
With Range("Y" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
End With
LastRow = LastRow + 1
Next tableStart
.Close False
End With
Next FileName
WordApp.Quit
Set WordDoc = Nothing
Set WordApp = Nothing
End Sub
It is working but having only one issue. if a cell is having multiple paragraph then it's getting pasted in multiple row of excel. I want like if 2nd column of 1st row of word file is having 3 paragraph, then in excel as well all these 3 paragraph should get pasted in same column.
Word Input
Excel File Output
Hope I am able to explain it properly.
I have amended your script to produce the desired results.
The clear contents and targeting is removed as this will allow other word tables to be added to the same sheet, amend the script if you want to clear the sheet each time.
The table start selection now works by setting the tableNo as the start of the loop
It pulls the heading from the first column of the first selected tableNo
VBA Script:
Sub ImportWordTable()
Dim WordApp As Object
Dim WordDoc As Object
Dim arrFileList As Variant, FileName As Variant
Dim tableNo As Integer 'table number in Word
Dim tableStart As Integer
Dim tableTot As Integer
Dim LastRow As Long
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
'On Error Resume Next
arrFileList = Application.GetOpenFilename("Word files (*.doc; *.docx),*.doc;*.docx", 2, _
"Browse For file containing table To be imported", , True)
If Not IsArray(arrFileList) Then Exit Sub '(user cancelled import file browser)
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
'Range("A:AZ").ClearContents
For Each FileName In arrFileList
Set WordDoc = WordApp.Documents.Open(FileName, ReadOnly:=True)
With WordDoc
tableNo = WordDoc.tables.Count
tableTot = WordDoc.tables.Count
If tableNo = 0 Then
MsgBox WordDoc.Name & " contains no tables", vbExclamation, "Import Word Table"
ElseIf tableNo > 1 Then
tableNo = InputBox(WordDoc.Name & " contains " & tableNo & " tables." & vbCrLf & _
"Enter the table To start from", "Import Word Table", "1")
End If
' Set the header for the Colums
With .tables(tableNo)
Parent.Range("A" & LastRow).Value = .Cell(1, 1).Range
Parent.Range("B" & LastRow).Value = .Cell(2, 1).Range
Parent.Range("C" & LastRow).Value = .Cell(3, 1).Range
End With
LastRow = LastRow + 1
' Get the date from the tables
For tableStart = tableNo To tableTot
With .tables(tableStart)
.Cell(1, 2).Range.Copy
With Range("A" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.Cell(2, 2).Range.Copy
With Range("B" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
.Cell(3, 2).Range.Copy
With Range("C" & LastRow)
.Select
.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False
.Borders.LineStyle = xlLineStyleNone
End With
End With
LastRow = LastRow + 1
Next tableStart
.Close False
End With
Next FileName
WordApp.Quit
Set WordDoc = Nothing
Set WordApp = Nothing
End Sub
As I said in my above comment, one Word table column cannot copy directly, not having a range property. Two ways are recommended, to avoid copying of each table cell, which consumes Excel resources and is very slow. One way would be to select the respective column (VBA allows it) and copy/paste selection. But using clipboard it is slow for more involved documents.
The most efficient way is to place the column range in an array (working only in memory) and drop its content, at once, in the necessary range. Then, try to format it. Copying the format from Word is also slow and consumes resources. I used a trick: Transforming the dropped array content range in an listObject, then UnList it. To benefit of the standard table format. If you need them to be tables, you have to comment the code line tbl.UnList:
Sub ImportWordTable()
Dim WordApp As Object, WordDoc As Object, ws As Worksheet
Dim arrFileList As Variant, FileName As Variant, tableNo As Integer
Dim tableStart As Integer, tableTot As Integer, Target As Range
Set ws = ActiveSheet 'it is good to fully qualify all the objects
'so, use here the sheet you need
arrFileList = Application.GetOpenFilename("Word files (*.doc; *.docx),*.doc;*.docx", 2, _
"Browse for file containing table to be imported", , True)
If Not IsArray(arrFileList) Then Exit Sub '(user cancelled import file browser)
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
ws.Range("A:A").Clear 'clear its format, too...
Set Target = ws.Range("A1")
Dim i As Long, tbl As ListObject
For Each FileName In arrFileList
Set WordDoc = WordApp.Documents.Open(FileName, ReadOnly:=True)
With WordDoc
tableNo = WordDoc.tables.count
tableTot = WordDoc.tables.count
If tableNo = 0 Then
MsgBox WordDoc.name & " contains no tables", vbExclamation, "Import Word Table"
ElseIf tableNo > 1 Then
tableNo = InputBox(WordDoc.name & " contains " & tableNo & " tables." & vbCrLf & _
"Enter the table to start from", "Import Word Table", "1")
End If
For tableStart = tableNo To tableTot 'start iteration from `tableNo` if not the default...
Dim arr: ReDim arr(1 To .tables(tableStart).rows.count, 1 To 1) 'declare and ReDim the necessary aray
With .tables(tableStart)
For i = 1 To .rows.count 'load the array with the second column content
arr(i, 1) = .Range.Columns(2).cells(i)
arr(i, 1) = left(arr(i, 1), Len(arr(i, 1)) - 1) 'eliminate the Word strange ending line character
Next i
With Target.Resize(.rows.count, 1)
.Value = arr
Set tbl = ws.ListObjects.Add(xlSrcRange, ws.Range(.address), , xlYes) 'make the range a table
tbl.Unlist 'just transforming the table in range, but keeping its format...
End With
Set Target = Target.Offset(.Rows.Count + 2) 'reset Target
End With
Next tableStart
.Close False 'close the open document, without saving it
End With
Next FileName
WordApp.Quit
Set WordDoc = Nothing: Set WordApp = Nothing
End Sub
Could someone sell me why I am getting a runtime error here?? I have almost this identical code in another project that works, and I cant figure out the issue.
Sub Create_PDF()
' Create and save .pdf
Dim pdfName As String
Dim myrange As String
myrange = Cells(Rows.Count, 6).End(xlUp).Address
Dim AccountNumber As String
AccountNumber = Right(A1, 3)
FullName = "P:\Public\Generated Letters\LTXN Export Spreadsheets\" & "AccountEnding" & AccountNumber & ".pdf"
'Sets the name and location for the new file
myrange = Cells(Rows.Count, 6).End(xlUp).Address
'sets the string end for the print area
With ActiveSheet.PageSetup
.PrintArea = "A1:" & myrange
.Orientation = xlLandscape
.Zoom = False
.FitToPagesTall = False
.FitToPagesWide = 1
End With
'Setting the spreadsheet to print active content with columns fit to single page
If Dir(FullName) <> vbNullString Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="P:\Public\Generated_Letters\LTXN_Export_Spreadsheets\" & "AccountEnding" & AccountNumber & " - " & Format(Now, "mm.dd.yyyy hh mm") & ".pdf" _
, Quality:=xlQualityMedium, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
Else
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="P:\Public\Generated_Letters\LTXN_Export_Spreadsheets\" & "AccountEnding" & AccountNumber & Format(Now, "mm.dd.yyyy hh mm") & ".pdf" _
, Quality:=xlQualityMedium, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
'###This is where I am getting the runtime error and the file is not saving###
End Sub
Sub openFolder()
'Open the folder that we save the PDF to
Call Shell("explorer.exe" & " " & "P:\Public\Generated Letters\LTXN Export Spreadsheets\", vbNormalFocus)
End Sub
The one difference from the other project is that AccountNumber is a number and not text, but I figured in defining it as a string it shouldnt matter???
Try this:
Option Explicit
'use Const for fixed values
Const EXPORTS As String = "P:\Public\Generated Letters\LTXN Export Spreadsheets\"
Sub Create_PDF()
Dim ws As Worksheet, myRange As Range
Dim AccountNumber As String, dt As String, FullName As String, fName As String, sep As String
Set ws = ActiveSheet
AccountNumber = Right(ws.Range("A1").Value, 3) 'not just `A1`
With ActiveSheet.PageSetup
.PrintArea = "A1:" & ws.Cells(Rows.Count, 6).End(xlUp).Address
.Orientation = xlLandscape
.Zoom = False
.FitToPagesTall = False
.FitToPagesWide = 1
End With
dt = Format(Now, "mm.dd.yyyy hh mm")
fName = EXPORTS & "AccountEnding" & AccountNumber
If Len(Dir(fName & ".pdf")) > 0 Then sep = " - "
fName = fName & sep & dt & ".pdf"
'note there's no `xlQualityMedium` enumeration for `Quality`
ws.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fName, _
Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
Sub openFolder()
'Folder paths with spaces need to be quoted....
Call Shell("explorer.exe" & " """ & EXPORTS & """", vbNormalFocus)
End Sub
I use a macro for over 2 years with no problems. The macro is simple - copy a table from an Excel file and paste it into a Word document. For a few days, I am struggling with a problem - after starting the macro
error 4198 is occurring.
After clicking Debug VBA highlights such part of the code:
myDoc.Paragraphs(17).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
When I click Continue, the macro is going to the end with no additional problems until the next iteration.
Here is the entire macro:
Sub Agent_info()
Dim w As MailMerge
Dim a As Integer
Dim NumberOfFiles As Integer
Dim sFileName As String
Dim xlTable As Excel.Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
Dim komorka As String
Dim my_xl As Excel.Workbook
Dim xlApp As Excel.Application
'NumberOfFiles = 3
NumberOfFiles = InputBox("Ile pism przygotować?", "Pytanie")
On Error GoTo ERR_Handler
Application.ScreenUpdating = False
Application.Visible = True
Set w = ActiveDocument.MailMerge
w.DataSource.ActiveRecord = wdFirstDataSourceRecord
Set xlApp = CreateObject("Excel.Application")
Dim xlPath As String
xlPath = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\ZAŁĄCZNIKI.xlsx"
xlApp.Visible = True
Set my_xl = xlApp.Workbooks.Open(xlPath)
Worksheets("info").Activate
Range("A1").Select
If Len(Dir("C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania", vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania"
End If
If Len(Dir("C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania\INFO", vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania\INFO"
End If
If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma", vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma"
End If
If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Pliki tymczasowe", vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Pliki tymczasowe"
End If
For a = 1 To NumberOfFiles
On Error Resume Next
Set xlApp = GetObject("Excel.Application")
Err.Clear
If xlApp Is Nothing Then Set xlApp = CreateObject("Excel.Application")
If Err.Number = 429 Then
MsgBox "Microsoft Excel could not be found, aborting."
End If
On Error GoTo 0
komorka = ActiveCell.Address
Do While ActiveCell.Value <> "Suma"
ActiveCell.Offset(1, 0).Select
Loop
ActiveCell.Offset(0, 1).Select
Set xlTable = Excel.Range(komorka, ActiveCell)
xlTable.Copy
Do While ActiveCell.Value <> "Zaległość"
ActiveCell.Offset(-1, 0).Select
Loop
ActiveCell.Offset(0, 1).Select
With w
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = a
.LastRecord = a
End With
.Execute Pause:=False
End With
Dim katalog As String
Dim folder As String
Dim sciezka1 As String
Dim sciezka2 As String
Dim PDF As String
Dim PDF2 As String
Dim nazwaPisma As String
Dim nazwa1 As String
Dim nazwa2 As String
katalog = w.DataSource.DataFields("NAZWA_PLIKU").Value
folder = w.DataSource.DataFields("DATA_DO_PISMA_rrrrmmdd").Value
'folder = Format(Date, "yyyy-mm-dd")
If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog, vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog
End If
If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder, vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder
End If
'MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog
'MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder
nazwaPisma = " informacja o stanie zaległości z dnia "
sciezka1 = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Pliki tymczasowe\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".docx"
sciezka2 = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder & "\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".docx"
PDF = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder & "\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".pdf"
PDF2 = "C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania\INFO\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".pdf"
ActiveDocument.Parent.ScreenUpdating = False
ActiveDocument.SaveAs _
FileName:=sciezka1, _
FileFormat:=wdFormatXMLDocument, _
LockComments:=False, _
Password:="", _
AddToRecentFiles:=True, _
WritePassword:="", _
ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, _
SaveFormsData:=False, _
SaveAsAOCELetter:=False
ActiveDocument.Close
On Error Resume Next
Set WordApp = GetObject(class:="Word.Application")
Err.Clear
If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
If Err.Number = 429 Then
MsgBox "Microsoft Word could not be found, aborting."
End If
On Error GoTo 0
WordApp.Visible = True
WordApp.Activate
Set myDoc = WordApp.Documents.Open(sciezka1)
myDoc.Paragraphs(17).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
'If Err.Number = 4198 Then
'MsgBox "Microsoft Word could not be found, aborting."
'End If
Set WordTable = myDoc.Tables(1)
WordTable.AutoFitBehavior (wdAutoFitWindow)
WordTable.Range.ParagraphFormat.SpaceAfter = 0
Set PasteSheet = Nothing
Documents(myDoc).SaveAs _
FileName:=sciezka2, _
FileFormat:=wdFormatXMLDocument, _
LockComments:=False, _
Password:="", _
AddToRecentFiles:=True, _
WritePassword:="", _
ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, _
SaveFormsData:=False, _
SaveAsAOCELetter:=False
ActiveDocument.ExportAsFixedFormat _
OutputFileName:=PDF2, _
ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, _
From:=1, To:=1, _
Item:=wdExportDocumentContent, _
IncludeDocProps:=True, _
KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, _
DocStructureTags:=True, _
BitmapMissingFonts:=True, _
UseISO19005_1:=False
ActiveDocument.ExportAsFixedFormat _
OutputFileName:=PDF, _
ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, _
From:=1, To:=1, _
Item:=wdExportDocumentContent, _
IncludeDocProps:=True, _
KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, _
DocStructureTags:=True, _
BitmapMissingFonts:=True, _
UseISO19005_1:=False
Documents(myDoc).Close
w.DataSource.ActiveRecord = wdNextRecord
Next
END_Handler:
Application.Visible = True
Application.ScreenUpdating = True
Exit Sub
ERR_Handler:
MsgBox Err.Description
Resume END_Handler:
End Sub
I currently have my macro to separate and create new workbooks for unique values by email address and add the unique value workbooks to a folder.
What I am now trying to do is add to this so that it will do the same thing with a slight twist. I need a folder to be created by a column containing an Organization name (There are about 100 different organizations) and then have it create new workbooks based off of unique values by email address (the same thing it currently does.) I just can't figure out how to add that extra folder of Organization name and still run as it does.
Most of the code I am using I found online, I made a couple slight modifications for my personal use.
Sub Copy_To_Workbooks()
Dim My_Range As Range
Dim FieldNum As Long
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim CalcMode As Long
Dim ViewMode As Long
Dim ws2 As Worksheet
Dim MyPath As String
Dim foldername As String
Dim Lrow As Long
Dim cell As Range
Dim CCount As Long
Dim WSNew As Worksheet
Dim ErrNum As Long
Set My_Range = Range("A1:Q" & LastRow(ActiveSheet))
My_Range.Parent.Select
If ActiveWorkbook.ProtectStructure = True Or _
My_Range.Parent.ProtectContents = True Then
MsgBox "Sorry, not working when the workbook or worksheet is protected", _
vbOKOnly, "Copy to new workbook"
Exit Sub
End If
FieldNum = 4
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
'Set the file extension/format
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2013
If ActiveWorkbook.FileFormat = 56 Then
FileExtStr = ".xls": FileFormatNum = 56
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
End If
'Change ScreenUpdating, Calculation, EnableEvents, ....
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
ActiveSheet.DisplayPageBreaks = False
'Delete the sheet RDBLogSheet if it exists
On Error Resume Next
Application.DisplayAlerts = False
Sheets("RDBLogSheet").Delete
Application.DisplayAlerts = True
On Error GoTo 0
' Add worksheet to copy/Paste the unique list
Set ws2 = Worksheets.Add(After:=Sheets(Sheets.Count))
ws2.Name = "RDBLogSheet"
'Fill in the path\folder where you want the new folder with the files
MyPath = “U:\Updates”
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
foldername = MyPath & Format("Helper Cases") & "\"
MkDir foldername
With ws2
'first we copy the Unique data from the filter field to ws2
My_Range.Columns(FieldNum).AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=.Range("A3"), Unique:=True
'loop through the unique list in ws2 and filter/copy to a new sheet
Lrow = .Cells(Rows.Count, "A").End(xlUp).Row
For Each cell In .Range("A4:A" & Lrow)
'Filter the range
My_Range.AutoFilter Field:=FieldNum, Criteria1:="=" & _
Replace(Replace(Replace(cell.Value, "~", "~~"), "*", "~*"), "?", "~?")
'Check if there are no more then 8192 areas(limit of areas)
CCount = 0
On Error Resume Next
CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible) _
.Areas(1).Cells.Count
On Error GoTo 0
If CCount = 0 Then
MsgBox "There are more than 8192 areas for the value : " & cell.Value _
& vbNewLine & "It is not possible to copy the visible data." _
& vbNewLine & "Tip: Sort your data before you use this macro.", _
vbOKOnly, "Split in worksheets"
Else
'Add new workbook with one sheet
Set WSNew = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
'Copy/paste the visible data to the new workbook
My_Range.SpecialCells(xlCellTypeVisible).Copy
With WSNew.Range("A1")
' Paste:=8 will copy the columnwidth in Excel 2000 and higher
' Remove this line if you use Excel 97
.PasteSpecial Paste:=8
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
.Select
End With
'Save the file in the new folder and close it
On Error Resume Next
WSNew.Parent.SaveAs foldername & _
cell.Value & FileExtStr, FileFormatNum
If Err.Number > 0 Then
Err.Clear
ErrNum = ErrNum + 1
WSNew.Parent.SaveAs foldername & _
"Error_" & Format(ErrNum, "0000") & FileExtStr, FileFormatNum
.Cells(cell.Row, "B").Formula = "=Hyperlink(""" & foldername & _
"Error_" & Format(ErrNum, "0000") & FileExtStr & """)"
.Cells(cell.Row, "A").Interior.Color = vbRed
Else
.Cells(cell.Row, "B").Formula = _
"=Hyperlink(""" & foldername & cell.Value & FileExtStr & """)"
End If
WSNew.Parent.Close False
On Error GoTo 0
End If
'Show all the data in the range
My_Range.AutoFilter Field:=FieldNum
Next cell
.Cells(1, "A").Value = "Red cell: can't use the Unique name as file name"
.Cells(1, "B").Value = "Created Files (Click on the link to open a file)"
.Cells(3, "A").Value = "Unique Values"
.Cells(3, "B").Value = "Full Path and File name"
.Cells(3, "A").Font.Bold = True
.Cells(3, "B").Font.Bold = True
.Columns("A:B").AutoFit
End With
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
If ErrNum > 0 Then
MsgBox "Rename every WorkSheet name that start with ""Error_"" manually" _
& vbNewLine & "There are characters in the name that are not allowed" _
& vbNewLine & "in a sheet name or the worksheet already exist."
End If
'Restore ScreenUpdating, Calculation, EnableEvents, ....
My_Range.Parent.Select
ActiveWindow.View = ViewMode
ws2.Select
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlValues, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
I'm working vba macro which works perfectly but I need save the documents as .pdf.
I´m searching for tips, but I don´t know how to find them. Last time I found this solution : vba mail merge save as pdf
but I don´t know apply it to my macro.
Here is my code:
Sub RunMerge()
Dim wd As Object
Dim wdocSource As Object
Dim strWorkbookName As String
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then
Set wd = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wdocSource = wd.Documents.Open(ThisWorkbook.Path & "\" & "ArtSpecDatabase.docx")
strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
wdocSource.MailMerge.MainDocumentType = wdFormLetters
wdocSource.MailMerge.OpenDataSource _
Name:=strWorkbookName, _
AddToRecentFiles:=False, _
Revert:=False, _
Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
SQLStatement:="SELECT * FROM `Sheet2$`"
With wdocSource.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = 1
.LastRecord = 1
End With
.Execute Pause:=False
End With
Dim PathToSave As String
PathToSave = ThisWorkbook.Path & "\" & "pdf" & "\" & Sheets("Sheet2").Range("B2").Value2 & ".docx"
If Dir(PathToSave, 0) <> vbNullString Then
wd.FileDialog(FileDialogType:=msoFileDialogSaveAs).Show
Else
wd.activedocument.SaveAs2 PathToSave, wdFormatDocumentDefault
End If
wd.Visible = True
wdocSource.Close savechanges:=False
wd.activedocument.Close savechanges:=False
Set wdocSource = Nothing
Set wd = Nothing
End Sub
To export a Word document as PDF, you need to use the ExportAsFixedFormat method. For example, you can replace your SaveAs2 call with this:
wd.ActiveDocument.ExportAsFixedFormat PathToSave, 17 'The constant for wdExportFormatPDF
Now, your call to FileDialog makes no sense, so I propose changing the entire Dir(...) If-sentence to this:
Dim PathToSave As String
PathToSave = ThisWorkbook.Path & "\" & "pdf" & "\" & Sheets("Sheet2").Range("B2").Value2 & ".pdf"
If Dir(PathToSave, 0) <> vbNullString Then
With wd.FileDialog(FileDialogType:=msoFileDialogSaveAs)
If .Show = True Then
PathToSave = .SelectedItems(1)
End If
End With
End If
wd.ActiveDocument.ExportAsFixedFormat PathToSave, 17 'The constant for wdExportFormatPDF
EDIT: Forgot to include ".pdf" extension.
Use the below code to export excel to pdf
Sub tst1()
Dim fFilename As String
fFilename = "C:\Documents and Settings\test.xlsx"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
fFilename & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
End Sub