Spark Lines and DO-loops - vba

I have a workbook with several sheets.
One of the sheets "Calc" summarizes the data for 8 spark lines I have presented on a summary page based on an employee ID number entered on the summary page.
I have a created DO-loop macro to run this summary sheet by employee ID# and convert to a PDF and save by ID number.
Works like a charm and saves hours of time (literally). Trouble is two of the spark lines will not update.
I feel like Excel going to fast to allow them to update.
I have tried to put in a delay, Application.Wait(Now + TimeValue("00:00:01")), and have gone up to two minutes... No luck. Any ideas?
Option Explicit
Sub PDFtool()
On Error GoTo errorHandle:
Dim i As Integer
i = 2
Dim main, dataname, path, filename, ID As String
path = Cells(5, 4)
main = ActiveWorkbook.Name
filename = ActiveWorkbook.path & "\" & "PDF files " & Format(Now(), "yyyy mm dd hh mm")
MkDir filename
Workbooks.Open filename:=path
dataname = ActiveWorkbook.Name
Do
Worksheets("AM Location & ID#").Activate
If Cells(i, 1) = "" Then Exit Do
ID = Cells(i, 3)
Worksheets("AM").Activate
Cells(190, 1) = ID
Worksheets("AM").Calculate
ActiveSheet.ListObjects("Table33").Range.AutoFilter Field:=1, Criteria1:= _
"TRUE"
Columns("H:N").Select
Selection.EntireColumn.Hidden = True
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename & "/" & ID & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Columns("G:S").Select
Selection.EntireColumn.Hidden = False
ActiveSheet.ListObjects("Table33").Range.AutoFilter Field:=1
i = i + 1
Loop
Application.ScreenUpdating = True
End
errorHandle:
Application.ScreenUpdating = True
MsgBox ("ERROR! Call Greg")
End
End Sub

Related

Why am I getting a type mismatch on this MyCell range error?

I keep getting a runtime error on this line:
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=MgrPath & "2018 Mid-Year Comp Statement - " & SM.Range("C5").Value & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Sub Statement_Autoprint()
Dim MCST As Workbook: Set MCST = ActiveWorkbook
Dim User As String: User = Environ$("Username")
Dim SavePath As String: SavePath = "M:\comp_statements\"
Dim CS As Worksheet: Set CS = MCST.Sheets("Control Sheet")
Dim MgrPath As String, MyCell As Range, Printed As Integer, i As Integer, SM As Worksheet
Printed = 0
Call Disable
For i = 2 To CS.Range("B" & CS.Rows.Count).End(xlUp).Row
If CS.Range("A" & i) <> "" & CS.Range("B" & i) <> "" Then
Set SM = MCST.Sheets(CStr(CS.Range("A" & i)))
SM.Calculate
SM.Range("P1") = Format(CS.Range("B" & i), "000000000")
For Each MyCell In SM.Range("N2:N70")
If MyCell = "HIDE" Then
MyCell.EntireRow.Hidden = True
ElseIf MyCell <> "HIDE" Then
MyCell.EntireRow.Hidden = False
End If
Next MyCell
If Not Application.CalculationState = xlDone Then
DoEvents
End If
MgrPath = "M:\Pittsburgh\GRP4\HR_PCorpComp\2018 Midyear\Reporting\Parsley\comp_statements\" & SM.Range("K5") & "\"
If Dir(MgrPath, vbDirectory) <> "" Then
MkDir MgrPath
End If
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=MgrPath & "2018 Mid-Year Comp Statement - " & SM.Range("C5").Value & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Printed = Printed + 1
End If
Next i
CS.Activate
Call Re_Enable
End Sub
I do not have any files that exist/are open under that name, I have no clue what could be preventing this from saving. All of the other bits of code do what they're supposed to, it just can't loop to the next employee because the save is being suppressed because of that error.
Try this
For Each mycell In SM.Range("N2:N70")
If IsError(mycell) Then
Debug.Print mycell.Address
Else
mycell.EntireRow.Hidden = (mycell = "HIDE")
End If
Next mycell
Either handle the error using IsError or
Go to the cell which the above code points to and check if there are any formula errors.
You usually get that error if the cell has formula errors.

VBA - printing individual sheets as individual and combined pdf

Dim s As String
Dim i As Long
Dim rng As Range
Dim ws() As Variant 'dynamic array
If LCase(Sheet76.Range("H7")) = "x" Then
ReDim ws(1 To 7) 'declare size
'Select file save location
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
strPath = .SelectedItems(1)
End If
End With
'to print individually
For i = 1 To 7
s = Sheet76.Cells(8 + i, 7).Value
ws(i) = s
Sheets(s).Select
strPath = strPath & "\"
strFileName = strPath & s & ".pdf"
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strFileName, _
IgnorePrintAreas:=False
Next
end if
I have two questions. The above code is for printing out individual pdfs per worksheet. I'm able to print out 4 of the 7, then it has an error runtime message. What am I doing wrong?
Also, why doesn't this work for printing out multiple worksheets as a single pdf?
sheets(ws).select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strFileName, _
IgnorePrintAreas:=False`
EDIT: I fixed the runtime error; the string value for i=5 didn't tie up with the sheet name. I'm still stuck on how to print the selected worksheets as one combined pdf.
dim ws() as string
For i = 1 To 7
s = Sheet76.Cells(8 + i, 7).Value
ws(i) = s
Next
Sheets(ws).Select
strFileName = strPath & "Combined.pdf"
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strFileNamering variable., _
IgnorePrintAreas:=False
Solution to printing worksheets as a single combined pdf above. I got it to work by declaring ws() array as st

Excel VBScript to close the openeded and previously printed PDF before printing to another PDF

I am printing worksheets to one single PDF file with one chunk of code. With this PDF file open, If I attempt another print to PDF from this same excel file I get a VB error: "Document not saved" and debug takes me here in the code:
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
strFilename & " " & wedate_text & " Time", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
HERE IS CODE:
Sub PrintAnadarkoTicketsToPDF()
Worksheets("Cover").Visible = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
Dim strFilename As String
Dim rngRange As Range
Dim wedate As Date
Dim wedate_text As String
Set rngRange = Worksheets("Cover").Range("A5")
strFilename = rngRange.Value
wedate = Worksheets("Cover").Range("B24").Value
wedate_text = Format$(wedate, "mm.dd.yyyy")
Dim myArray() As Variant
Dim i As Integer
Dim j As Integer
j = 0
For i = 1 To Sheets.Count
If Sheets(i).Visible = True Then
ReDim Preserve myArray(j)
myArray(j) = i
j = j + 1
End If
Next i
Sheets(myArray).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
strFilename & " " & wedate_text & " Time", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
Worksheets("Cover").Visible = True
Sheets(1).Select
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
End Sub
My question is: How do I print this second PDF without crashing the script? I would like to close the previous PDF or create the second PDF with a different file name. Thanks for the suggestions.
Randy
I'm not sure why you want to have a loop that counts the number of non-hidden sheets. Plus, you could export the sheets inside that loop. That may fix your issue:
For i = 1 To Sheets.Count
If Sheets(i).Visible = True Then
Sheets(i).ExportAsFixedFormat Type:=xlTypePDF, filename:= _
strFilename & Trim(Str(i)) & " " & wedate_text & " Time", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End If
Next i
Note also the addition of the workbook number to the file name, because it's trying to save to the same file.

exporting a certain worksheet from a workbook to pdf

i am an amateur programmer learning how to program using vba
without further a due, my question is :
i have created a listbox (listbox1) where i've listed all my sheets(ws) name in a specific workbook.
i've also created another listbox(listbox2) where when i select some sheets name on the listbox1, they will be transfer to listbox2.
my main objective is that by choosing one or more sheets listed in the listbox2, and by clicking a button, i'll manage to save all the selected sheets in one pdf file.
here is the code for the button used to export the file in pdf that i've written but i've only managed to export them not in one pdf file but in numerous amount of pdf file.
Dim NomTableau() As String
For Each WkbkName In application.Workbooks()
If WkbkName.Name = choix_poteau.Value & "_" & section & "_" & projet & ".xlsx" Then
WkbkName.Activate
GoTo lois
End If
Next
Set wbk = Workbooks.Open(add1 & "\" & Me.projet.Value & "\" & Me.section.Value & "\poteaux\" & Me.choix_poteau.Value & "_" & Me.section & "_" & Me.projet & ".xlsx")
lois:
For i = 0 To ListBox2.ListCount - 1
While ListBox2.List(i) <> ""
Dim ws As Worksheet
For Each ws In Worksheets
If ws.Name = ListBox2.List(i) Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Export\Resultats__" & ListBox2.List(i - counter) & ".pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End If
Next
Wend
Next i
End Sub
thanks alot, really appreciate your help
Instead of exporting each sheet individually, select them all first and then call the ExportAsFixedFormat method.
Here is my test code, which worked as expected:
Option Explicit
Private Sub TestPDF()
Dim i As Integer
Dim arrSheets() As String
Dim strSheets As String
'Get our sheet names
For i = 1 To 3
strSheets = Worksheets(i).Name & "," & strSheets
Next
'Trim the trailing comma
strSheets = Left(strSheets, Len(strSheets) - 1)
arrSheets = Split(strSheets, ",")
ThisWorkbook.Sheets(arrSheets).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\qzbcjs\Documents\Useful Workbooks\test.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub
I declared an array of strings, populated a string variable with the comma-delimited names of the worksheets (in my case I just wanted the first through third sheets), split that comma-delimited string into an array and used the array to select all of the desired sheets and only called the ExportAsFixedFormat method once.
Adapting this method to your code, beginning as the lois part would look something like this:
lois:
Dim ws As Worksheet
Dim arrSheets() As String
Dim strWs As String
For i = 0 To ListBox2.ListCount - 1
While ListBox2.List(i) <> ""
For Each ws In Worksheets
If ws.Name = ListBox2.List(i) Then
strWs = ws.Name & "," & strWs
End If
Next
Wend
Next i
strWs = Left(strWs, Len(strWs) - 1)
arrSheets = Split(strWs, ",")
ThisWorkbook.Sheets(arrSheets).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Export\Resultats__" & ListBox2.List(i - counter) & ".pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True

Convert Xls to Csv for a Range of Cells

I have a VBA Macro to convert all .xls files present in a folder to .csv files , but there is some additional requirement to be done.
I have to select a range of columns (like from A to AQ and all the rows) and to save them into .CSV files, I tried it through Macro recording but it didn't help.
Sub ConvertXLStoCSVNoRules(mySourcePath)
Set MyObject = New Scripting.FileSystemObject
Set strInputFolder = MyObject.GetFolder(mySourcePath)
'Set strOutputFolder = MyObject.GetFolder(myKeywordPath)
'Call DelFolder
strInputFolder = strInputFolder & "\"
MkDir (ThisWorkbook.Path & "\Sales")
MkDir (ThisWorkbook.Path & "\Group")
strOutputFolderGroup = ThisWorkbook.Path & "\Group\"
strOutputFolderSales = ThisWorkbook.Path & "\Sales\"
strXLSFile = Dir(strInputFolder & "*.xls*")
counter = 0
row = 24
Worksheets("Main").Cells(row, 1).Value = "Files processed at " & Now
row = row + 1
On Error Resume Next
Do While strXLSFile <> ""
counter = counter + 1
row = row + 1
If InStr(1, strXLSFile, "Sales") <> 0 Then
'strCSVFile contains Sales Then
'strCSVFile = Left(strXLSFile, InStrRev(strXLSFile, ".")) & "csv"
On Error Resume Next
strCSVFile = Left(strXLSFile, 4) & " Sales" & ".csv"
'Add into the first sheet for recording purpose
Worksheets("Main").Cells(row, 1).Value = strXLSFile
Workbooks.OpenText strInputFolder & strXLSFile
Range("A1:AQ1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveWorkbook.SaveAs strOutputFolderSales & strCSVFile, xlCSV, CreateBackup:=False
ActiveWindow.Close
Application.DisplayAlerts = False
ActiveWorkbook.Close False
strXLSFile = Dir
ElseIf InStr(1, strXLSFile, "Group") <> 0 Then
strCSVFile = Left(strXLSFile, 4) & " Group" & ".csv"
'Add into the first sheet for recording purpose
Worksheets("Main").Cells(row, 1).Value = strXLSFile
Workbooks.OpenText strInputFolder & strXLSFile
Range("A1:AQ1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveWorkbook.SaveAs strOutputFolderSales & strCSVFile, xlCSV, CreateBackup:=False
ActiveWindow.Close
Application.DisplayAlerts = False
ActiveWorkbook.Close False
strXLSFile = Dir
Else
Worksheets("Main").Cells(row, 1).Value = strXLSFile & " Not Processed"
End If
Loop
'MsgBox ("Files completed " & counter)
row = row + 1
Worksheets("Main").Cells(row, 1).Value = "Files completed " & counter & " at " & Now
End Sub
No error while executing code. Data does not get copied from excel files to .csv files. Excel files opened for copying are not getting closed.
Any solution would be helpful
Comments:
I have the full block of code , Now the folder containing the xls files will be segregated based on names as sales and group after converting to csv, but the converted csv files are of 1kb doesnt have any data except few junk .
Thanks in advance
What you are currently selecting is the last Row used not all the rows. You can either write
Range("A1:AQ" & lnDyRw).select which will select everything between A1 and AQ lnDyRw
or to Select a Range of Columns you can write:
Range("A:AQ").select
At the moment you should have the last line somewhere in your new workbook.