Frozen pane gets partially cropped when exporting to PDF - excel

I'm exporting from an excel range with frozen pane at the top to a PDF file through VBA.
In my Page Layout, Width is set to 1 page, and Height is on Automatic.
For some reason though, the two first rows of my frozen pane get cropped in all pages of PDF but the first one.
First page:
Other pages:
Here is the code used to export (pretty straightforward):
lastRow = getLastRow(targetWksht) 'targetWksht is well defined elsewhere
lastCol = getLastCol(targetWksht)
With targetWksht.Range(targetWksht.Cells(1, 1), targetWksht.Cells(lastRow, lastCol))
.ExportAsFixedFormat Type:=xlTypePDF, _
fileName:=Application.ActiveWorkbook.Path & "\" & fileName, _ 'fileName is defined elsewhere
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=True, _
OpenAfterPublish:=True
End With
It might be something stupid, but do you know where it may come from and how to fix that?

Try $worksheet.PageSetup.FitToPagesTall = 9999 instead of automatic or set your margins with code.

I found where it came from.
The frozen pane was selected as page title, but for some reason not all rows in this title were supposed to be repeated in following pages.
Therefore, the title appeared complete in the first page, but only partial in other ones.
To solve the problem, if you encounter it, follow this:
In Excel, go to Page Layout > Page Setup > Print Titles. You will have Print Area, which is the title, and below, Rows to repeat at top.
Make sure that all rows from your title are selected. For some reason my default parameter started at 3 instead of 1, setting it at 1 solved the problem.
NB: It also works for columns at left.

Related

Use the text of a cell as the argument of range() with structured references

I want to execute an advanced filter with vba. The problematic step is that the name of the source table (for the advanced filter) is written in a cell and it seems I can't find a way to pass it to range().
Here is the idea:
The F5 cell contain "DatePlace" and it is the name of the table that should be used in the advanced filter. By recording a macro I saw that we could use structured references in VBA but when I try to take the reference from the value of F5, the advanced filter doesn't execute anymore.
I receive this error message box (translated from french) :
Execution error '1004':
Error defined by the application or by the object
Here is one of my attempts :
Worksheets("Planning")
.Range(Worksheets("Macro").Range("$F$5").Text & "[[#Headers],[#Data]]")
.AdvancedFilter Action _:=xlFilterCopy,
CriteriaRange:=Worksheets("Planning").Range("E7:F8"),
CopyToRange:=Worksheets("Planning").Range( _"E11:F11"), Unique:=False
I tried with .Value instead of .Text. I tried to pass it with a string variable too. I also tried to write the full reference in the F5 cell. And when I tried to get a range variable I just moved the issue to that variable initiation.
Any help is welcomed.
Edit 1 :
This way of doing it works but I have to hard code the structured reference and that's exactly what I want to avoid.
Worksheets("Planning")
.Range("DateLieu[[#Headers],[#Data]]")
.AdvancedFilter Action _:=xlFilterCopy,
CriteriaRange:=Range("A6:B7"),
CopyToRange:=Range( _"A10:B10"), Unique:=False
Edit 2 :
It should have worked without issue. Here is how the code looks now.
' Variables
Dim rngPlanning As String
' Initiations
rngPlanning = ThisWorkbook.Worksheets("Macro").Range("$F$5").Text & "[[#Headers],[#Data]]"
' Actions
Application.CutCopyMode = False
Debug.Print (rngPlanning)
Worksheets("Planning").Range(rngPlanning).AdvancedFilter _
Action:=xlFilterCopy, _
CriteriaRange:=Worksheets("Macro").Range("$E$7:$F$8"), _
CopyToRange:=Worksheets("Macro").Range("$E$11:$F$11"), _
Unique:=False

How to get a specific statement from a PDF using selenium with VBA

This is a continuity question of the below link. https://stackoverflow.com/a/56649098?noredirect=1
I need to do two things
1. Copy all text from PDF and paste it to the excel
2. Copy multiple lines and run a loop to find the text I need
The background of my project - I am opening a webpage with user credentials, after couples of clicks a PDF is opened in the browser. So now I need to get a particular statement from it. The problem is that the PDF is dynamic and the statement I require keeps changing (the line sometimes it is in 6th and sometimes in 9th or 10th and 11th) so the 2 things which I mentioned above will help me I am aware both sounds the same but it is different. Below is the code I used to get a particular statement, but how do I create a loop through all the statement or get multiple statements.
Const statext As String = _
"addEventListener('message',function(e){" & _
" if(e.data.type=='getSelectedTextReply'){" & _
" var txt=e.data.selectedText;" & _
" callback(txt && txt.match(/[^\r\n]+/g)[7]);" & _
" }" & _
"});" & _
"plugin.postMessage({type:'initialize'},'*');" & _
"plugin.postMessage({type:'selectAll'},'*');" & _
"plugin.postMessage({type:'getSelectedText'},'*');"
Casestatus = bot.ExecuteAsyncScript(statext)
I am very new to programming and automation so I may be missing a basic thing. Kindly pardon me.

Opening CSV as worksheet with VBA - incorrect parsing

I have some file.csv. If I open it by double-click, it opens in Excel with the proper setup (there are no semicolons and each "line" of data is correctly showing up in the expected columns).
Example result:
However, in VBA:
'Workbooks.OpenText Filename:=f, StartRow:=2, DataType:=xlDelimited, Semicolon:=True, ConsecutiveDelimiter:=True, TextQualifier:=xlTextQualifierNone
'Workbooks.OpenText Filename:=f, DataType:=xlDelimited, Semicolon:=True
'Workbooks.OpenText Filename:=f, DataType:=xlDelimited
'Workbooks.Open Filename:=f, Format:=xlDelimited, Delimiter:=Chr(34)
'Workbooks.Open Filename:=f, Format:=xlDelimited, Delimiter:=";"
Workbooks.Open Filename:=f, Format:=xlDelimited
Dim s As String
s = """" & ";" & """"
Workbooks.Open Filename:=f, Format:=xlDelimited, Delimiter:=s
'Workbooks.OpenText Filename:=f, DataType:=xlDelimited, OtherChar:=s
'Workbooks.OpenText Filename:=f, DataType:=xlDelimited, OtherChar:=";"
I've tried the lines above (and a number of others before I started keeping all my attempts) as well as without any arguments at all, but no matter what I do, the file will open without the text being split as it does when I double-click the file.
Example result:
So in summary; double-clicking the file parses the file correctly, Open and OpenText does not. Surprisingly, the worksheet looks identical regardless of using Open or OpenText.
A similar problem is described in this question, though it remains without a proper answer. The difference between our cases is that Excel won't parse anything for me, where it seems like it does parse large parts of the file for OP.
I just want to open the workbook and iterate over one of the columns, then close it. I have a couple of workarounds in mind, so I will be able to solve it one unnecessarily roundabout way or another.
So far I have found these ideas:
Renaming .csv to .txt and using OpenText
Using QueryTable import
Iterating over the borked file as it appears using OpenText and using LEFT/MID/RIGHT to get at the desired column(s)
Binary Open and Split each line into an array
Desired answers:
How to achieve this solution using Workbooks.OpenText or similar native function.
Explanations (or maybe even ideas) as to why Workbooks.OpenText and/or the most appropriate native function similar to it cannot achieve the desired result when Excel itself does seem to be capable of it.
Other workarounds.
If you are going to use VBA to import the file, just use VBA to parse the records:
Sub ImportFile()
Dim j As Long, k As Long
Close #1
Open "C:\TestFolder\whatever.csv" For Input As #1
j = 1
Do While Not EOF(1)
Line Input #1, TextLine
ary = Split(TextLine, ";")
k = 1
For Each a In ary
Cells(k, j) = a
k = k + 1
Next a
j = j + 1
Loop
Close #1
End Sub
Doing it this way stops VBA from assigning special meaning to the .csv extension.
Once the core code is working to your satisfaction, you can decorate it with other features like double-quote encapsulation, etc.
Thanks to #GarysStudent for inadvertently tipping me off as to the one attribute I had not been smart enough to try. They said "assigning special meaning to the .csv extension".
Turns out that localization impacts this "special meaning" in the .csv context. I am using a localized version of Excel and setting Local:=True enables both Open and OpenText to parse the file correctly, even without specifying ; as a delimiter.

Set Fit to Visible in Pdf from excel vba

I am trying to export excel worksheets into pdf. Is there any way by which I can set the pdf property to fit to visible using VBA.
Thanks
Below is the code snippet which I am using
With wksSalesAndQuotaScoreCard
'.PageSetup.LeftMargin=Application.InchesToPoints(0.7)
.PageSetup.LeftMargin = Application.InchesToPoints(0.7)
.PageSetup.RightMargin = Application.InchesToPoints(0.7)
.PageSetup.TopMargin = Application.InchesToPoints(0.75)
.PageSetup.BottomMargin = Application.InchesToPoints(0.75)
.PageSetup.HeaderMargin = Application.InchesToPoints(0.3)
.PageSetup.Orientation = xlLandscape
.PageSetup.PrintTitleRows = "_SalesandQuotaScoreCardView"
.PageSetup.CenterHorizontally = True
.PageSetup.Order = xlDownThenOver
.PageSetup.FitToPagesWide = 1
''.PageSetup.Zoom = 50
Set rngSalesAndQuotaView = Range(.Shapes("_SalesandQuotaViewFrame").TopLeftCell.Offset(0, -1), .Shapes("_SalesandQuotaViewFrame").BottomRightCell.Offset(1, 0))
rngSalesAndQuotaView.Select
End With
wksScoreCardPayoutView.Select
wksSalesAndQuotaScoreCard.Select False
Selection.ExportAsFixedFormat xlTypePDF, IncludeDocProperties:=True, openafterpublish:=True
wksCustomizeScoreCard.Activate
Adobe has a set of codes you can use when opening a document:
http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf
Be advised, these only work with the approved Adobe Reader and not all PDF readers will accept these commands.
You might have to have Acrobat to set the conditions manually per this answer on the Adobe Help Forums:
Regarding the OP: "How can I set the default to open all PDF's at 100%
zoom magnification?"
With Acrobat Pro, run a Batch Process (Sequence)/Action to run the
"Open Options" sequence. This sequence permits setting the values for
all items under the Initial View tab of PDFs' Document Properties.
Regarding a PDF's Document Properties > Initial View: Visit an open
PDF's Document Properties (Ctrl+D, Cmd+D). Go to the Initial View tab.
The top pane (Layout and Magnification) permits configuration of:
Navigation tab: Page Only | Bookmarks Panel and Page | Pages Panel and
Page | Attachments Panel and Page | Layers Panel and Page Page Layout:
Default | Single Page | Single Page Continuous | Two-Up (Facing) |
Two-Up (Cover Page) | Two-Up Continuous (Cover Page) Magnification:
Default | Actual Size | Fit Page | Fit Width | Fit Height | Fit
Visible | Magnification percentages (25% to 6400%)
Configuration settings other than "Default" dictate how the PDF is
viewed initially.
The settings for all values in all panes in the Initial View may be
established for one or many PDFs by use of a Batch Sequence/Action
(Acrobat Pro required).
This functionality is utilized in an enterprise environment where
large document collections are deployed in a LAN/WAN "eLibrary" to
provide a consistent initial view to end-users.
It also provides a content author a mechanism for establishing the
initial view for their deployed content (such as PDF document
collections distributed on optical storage media).
As to the typical default Initial View for a created PDF: When a PDF
is created via Acrobat the PDF document's default Initial View for
Layout and Magnification is:
--| Navigation: Page Only
--| Page layout: Default
--| Magnification: Default
--| Open to page: 1
Regarding the Open Parameters document — While this document does
provide a few command line options the document's primary focus is the
use of a URL to open a URL's targeted PDF's initially opening.
Worth noting is that the document is specific for URLs and not
applicable to UNC links (links with a LAN/WAN).
If I have understood your request, you need your print area (because exporting to PDF it's like printing) to adjusted both on width and height. You have the .PageSetup.FitToPagesWide = 1 statement, now you need also .FitToPagesTall = 1, so your code will look like:
With wksSalesAndQuotaScoreCard
'.PageSetup.LeftMargin=Application.InchesToPoints(0.7)
.PageSetup.LeftMargin = Application.InchesToPoints(0.7)
.PageSetup.RightMargin = Application.InchesToPoints(0.7)
.PageSetup.TopMargin = Application.InchesToPoints(0.75)
.PageSetup.BottomMargin = Application.InchesToPoints(0.75)
.PageSetup.HeaderMargin = Application.InchesToPoints(0.3)
.PageSetup.Orientation = xlLandscape
.PageSetup.PrintTitleRows = "_SalesandQuotaScoreCardView"
.PageSetup.CenterHorizontally = True
.PageSetup.Order = xlDownThenOver
.PageSetup.FitToPagesWide = 1
.FitToPagesTall = 1
''.PageSetup.Zoom = 50
Set rngSalesAndQuotaView = Range(.Shapes("_SalesandQuotaViewFrame").TopLeftCell.Offset(0, -1), .Shapes("_SalesandQuotaViewFrame").BottomRightCell.Offset(1, 0))
rngSalesAndQuotaView.Select
End With
If this is not the solution, please explain what is this fittovisible for you.
"Zoom Level" is not a document property for PDF files rather it is an application property. At the most, what we can do, open the PDF file directly from the excel macro and set the desired zoom level using "SendKeys".
Refer to the piece of code below which works for me:
Function PDFOpenFile(inPath As String, inPageNo As Long, inZoom As Variant)
'This function opens the PDF document with the specified
'Page number and zoom level
'The Page Number and Zoom Level are simulated through SendKeys method
' ************ Important *******************
' When the macro runs, do not use the keyboard
' else the SenKeys may not function as desired
ThisWorkbook.FollowHyperlink inPath, NewWindow:=True
SendKeys ("^+N" & inPageNo & "~^" & inZoom), True
End Function
Sub MyDocument()
' After file name, the firt parameter is for page no, the second parameter is for zoom level
PDFOpenFile "D:\MyFile.pdf", 3, 3
' Zoom Level Details
'0: Full Page
'1: Zoom to 100%
'2: Page Width
'3: Fit visible
'4: visible width / Reflow
' These zoom level are visible in acrobat reader. Go to "View > Zoom" and see the shortcut mentioned
' If the shortcuts are different for your case, you may modify the parameter passed as argument
End Sub
I printed a sheet, using PDFCreator, with "no scaling" and with "fit sheet on one page." The difference between the two was
.Zoom = 100
and
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
I think this going to be "printer" dependant though. When you simply Saveas PDF, you don't get those options, but the results aren't bad either.
Range("A1:H34").Select
Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\myfile.pdf", Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
I think much depends on how you are creating your PDF.
Print settings vary by computer because only the default printer defines what is the 'print area'. This is the same in Excel, Word, etc.
So you won't be able to define it for all computers, unless all the computers you are accessing the document on are set to the same default printer.
I think this is as print area setting you need to first set in excel before exporting to PDF. Do this in page layout first or within the "With" block of your code above and then run the code that exports to PDF.

How I can move part of text in MS Word with VBA to right side?

I need to write macro thats splits string into two parts. One part of text goes to left allign in word, second to right.
I found in this topic manual steps for doing it, my question is how to do it automatically?
https://superuser.com/questions/484261/word-formatting-need-to-align-left-to-left-right-to-right-in-same-line
I tried to make two text columns in Word:
With ActiveDocument.PageSetup.TextColumns
.SetCount NumColumns:=2
End With
but I don't know how to put my parts of text into desired column. Can anyone help me?
Try going to the developer tab and clicking 'Record Macro'. Then do the splitting manually. After that click 'Stop Recording'. This will give you the commands needed to automatically split the text.
With Constuntine help I found solution - in every line that I want to split to left and right side I do following action:
With objWord
.Visible = False
.Selection.TypeParagraph
.Selection.TypeText ("ABC" & vbTab & "123")
.Selection.ParagraphFormat.TabStops.Add Position:=CentimetersToPoints(17), _
Alignment:=wdAlignTabRight, Leader:=wdTabLeaderSpaces
End With

Resources