I have prepared a macro which works fine in demo sheet but gives a 1004 runtime error when it put it in the final sheet.
Below is my code:
Private Sub CommandButton3_Click()
'Declaring the Variables
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim rng As Range
Dim startdate As Long
Dim enddate As Long
Dim tbl As ListObject
Dim fname As Variant
'Assigning the Variables
Set ws = Sheets("Reports")
Set ws3 = Sheets("Report Format")
Set rng = ws.Range("E7")
startdate = ws.Range("L10").Value
enddate = ws.Range("L12").Value
'Find the Worksheet against the Name selected in Drop Down List
For Each ws1 In Worksheets
If rng.Value = ws1.Name Then
Sheets(rng.Value).Activate
End If
Next
'Filter the data based on the Date Range Entered
Set ws2 = ActiveSheet
Set tbl = ws2.ListObjects(1)
Range(tbl & "[[Date]:[Cheque #]]").Select
Selection.AutoFilter Field:=1, Criteria1:=">=" & startdate, Operator:=xlAnd, Criteria2:="<=" & enddate
Selection.Copy
ws2.Range("A10").Select
'Paste the Data in the Report Format
ws3.Activate
ws3.Range("B7").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
'Create the PDF of the Report
fname = Application.GetSaveAsFilename(InitialFileName:=rng.Value, filefilter:="PDF files, *.pdf", Title:="Export to PDF")
If fname <> False Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fname_, quality:=xlQualityStandard, includedocproperties:=True, ignoreprintareas:=False, openafterpublish:=True
End If
'Clear the Report format Sheet for Future Printing
With ActiveSheet
.Rows(10 & ":" & .Rows.Count).Delete
End With
'Activate the Report Sheet
ws.Activate
'Unfilter all the Tables present in Workbook
Dim w As Long
For w = 1 To Worksheets.Count
With Worksheets(w)
**.UsedRange.Cells.EntireRow.Hidden = False**
If .AutoFilterMode Then .ShowAllData
End With
Next w
End Sub
Error appears in line which is highlighted in commas. Kindly review and debug.
You are trying to concatenate a ListObject object into a string. You need the ListObject.Name property.
Dim ws2 As Worksheet, tbl As ListObject
Set ws2 = ActiveSheet
Set tbl = ws2.ListObjects(1)
Debug.Print tbl.Name
Range(tbl.Name & "[[Date]:[Cheque '#]]").Select
Please note that there is also a tick (aka ' or Chr(39)) escaping the hashmark in [Cheque '#].
Related
I have used bits and pieces of code on forums to create a macro that exports PDF's from a single sheet in excel. Each PDF contains the header and all relevant rows to the employee (all rows with employee ID). When I run it all goes well and the pdfs are correct, however the macro never stops running.
I believe I have created an infinite loop and am not sure how to correct it.
It also creates a PDF just containing the header that is not necessary.
Sub PracticeToPDF()
Dim ws As Worksheet
Dim ws_unique As Worksheet
Dim DataRange As Range
Dim iLastRow As Long
Dim iLastRow_unique As Long
Dim UniqueRng As Range
Dim Cell As Range
Dim LastRow As Long
Dim LastColumn As Long
Application.ScreenUpdating = False
'Note that the macro will save the pdf files in this active directory so you should save in an appropriate folder
DirectoryLocation = ActiveWorkbook.Path
Set ws = Worksheets("BootVSPayroll") 'Amend to reflect the sheet you wish to work with
Set ws_unique = Worksheets("BootVSPayroll") 'Amend to reflect the sheet you wish to work with
'Find the last row in each worksheet
iLastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
iLastRow_unique = ws_unique.Cells(Rows.Count, "A").End(xlUp).Row
With ws
'I've set my range to reflect my headers which are fixed for this report
Set DataRange = ws.Range("$A$1:$K$1" & iLastRow)
'autofilter field is 4 as I want to print based on the practice value in column D
DataRange.AutoFilter Field:=1
Set UniqueRng = ws_unique.Range("A1:A20" & iLastRow_unique)
For Each Cell In UniqueRng
DataRange.AutoFilter Field:=1, Criteria1:=Cell
Name = DirectoryLocation & "\" & Cell.Value & " BOOT Report" & ".pdf"
ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Name _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
Next Cell
End With
With ws
.Protect Userinterfaceonly:=True, _
DrawingObjects:=False, Contents:=True, Scenarios:= _
True, AllowFormattingColumns:=True, AllowFormattingRows:=True
.EnableOutlining = True
.EnableAutoFilter = True
If .FilterMode Then
.ShowAllData
End If
End With
Application.ScreenUpdating = True
End Sub
Did you perhaps mean for:
Set DataRange = ws.Range("$A$1:$K$1" & iLastRow)
...
Set UniqueRng = ws_unique.Range("A1:A20" & iLastRow_unique)
to instead be:
Set DataRange = ws.Range("$A$1:$K$" & iLastRow)
...
Set UniqueRng = ws_unique.Range("A1:A" & iLastRow_unique)
?
If, for example, (taken from ws_unique) your last used row, iLastRow_unique equals 200, then "A1:A20" & iLastRow_unique is equivalent to "A1:A20200" -- which may be a lot more rows that you intended to loop through, I think.
I convert multiple ranges on different worksheets to a single PDF.
Private Sub CommandButton1_Click()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim vFile As Variant
Dim sFile As String
Set ws1 = Worksheets("Sheet1")
ws1.PageSetup.PrintArea = "B2:K51"
Set ws2 = Worksheets("Sheet2")
ws2.PageSetup.PrintArea = "A3:J52, J3:S52, S3:AE52"
Worksheets(Array(ws1.Name, ws2.Name)).Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=vFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
End If
End Sub
The PrintArea range for ws2 creates a single range.
How do I separate the ranges so the output is three ranges instead of one?
Export to PDF
The solution inserts a new worksheet and copies the ranges to it. Then it exports the new worksheet to PDF and deletes the new worksheet.
Sheet Module e.g. Sheet1 (where the command button is)
Option Explicit
Private Sub CommandButton1_Click()
exportToPDF
End Sub
Standard Module e.g. Module1
Option Explicit
Sub exportToPDF()
' Define constants.
Const Gap As Long = 0
Const vFile As String = "F:\Test\Export.pdf"
Dim Ranges1 As Variant
Ranges1 = Array("B2:K51")
Dim Ranges2 As Variant
Ranges2 = Array("A3:J52", "J3:S52", "S3:AE52")
' Define workbook.
Dim wb As Workbook
Set wb = ThisWorkbook ' The workbook containing this code.
' Define worksheets.
Dim ws1 As Worksheet
Set ws1 = Worksheets("Sheet1")
Dim ws2 As Worksheet
Set ws2 = Worksheets("Sheet2")
Dim ws3 As Worksheet
Set ws3 = wb.Worksheets.Add(After:=wb.Sheets(wb.Sheets.Count))
' Copy ranges from first to third worksheet.
Dim rng As Range
Dim CurrRow As Long
CurrRow = 1
Dim j As Long
Dim RowsCount As Long
Dim ColsCount As Long
For j = LBound(Ranges1) To UBound(Ranges1)
Set rng = ws1.Range(Ranges1(j))
rng.Copy
ws3.Cells(CurrRow, 1).PasteSpecial xlPasteValues
ws3.Cells(CurrRow, 1).PasteSpecial xlFormats
If ColsCount < rng.Columns.Count Then
ColsCount = rng.Columns.Count
End If
CurrRow = CurrRow + rng.Rows.Count + Gap
Next j
' Copy ranges from second to third worksheet.
For j = LBound(Ranges2) To UBound(Ranges2)
Set rng = ws2.Range(Ranges2(j))
rng.Copy
ws3.Cells(CurrRow, 1).PasteSpecial xlPasteValues
ws3.Cells(CurrRow, 1).PasteSpecial xlFormats
If ColsCount < rng.Columns.Count Then
ColsCount = rng.Columns.Count
End If
CurrRow = CurrRow + rng.Rows.Count + Gap
Next j
' Export and close third worksheet.
With ws3
Set rng = .Range("A1").Resize(CurrRow - Gap - 1, ColsCount)
rng.Columns.AutoFit
.PageSetup.PrintArea = rng.Address
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=vFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True
End With
' Inform user.
MsgBox "PDF file has been created."
End Sub
Populate Data (Standard Module)
To quickly see what the code does:
Create a workbook containing worksheets Sheet1 and Sheet2.
Copy all three codes appropriately.
Run populateData.
Run exportPDF.
The Code
Private Sub populateData()
With [Sheet1!B2:K51]
.Formula = "=ROW()&""|""&COLUMN()"
.Interior.ColorIndex = 6
End With
With [Sheet2!A3:AE52]
.Formula = "=ROW()&""|""&COLUMN()"
.Interior.ColorIndex = 8
End With
End Sub
I have a workbook that has some 100,000+ number of lead records. Each record has an agent code which determines to whom the record is allotted to(50 plus agents). What I would like to do is to distribute all lead records per agent(workbook) depending on the agent code while also maintaining the existing data formatting, data validation and also automatically creating a worksheet password. Is this possible with excel VBA?
The table runs by this sequence:
enter image description here
EDIT:
Here are some of the sample scripts we ran:
Sub ExtractToNewWorkbook()
Dim ws As Worksheet
Dim wsNew As Workbook
Dim rData As Range
Dim rfl As Range
Dim state As String
Dim sfilename As String
Set ws = ThisWorkbook.Sheets("emp")
'Apply advance filter in your sheet
With ws
Set rData = .Range(.Cells(1, 1), .Cells(.Rows.Count, 11).End(xlUp))
.Columns(.Columns.Count).Clear
.Range(.Cells(2, 6), .Cells(.Rows.Count, 6).End(xlUp)).AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=.Cells(1, .Columns.Count), _
Unique:=True
For Each rfl In .Range(.Cells(1, .Columns.Count), .Cells(.Rows.Count, .Columns.Count).End(xlUp))
state = rfl.Text
Set wsNew = Workbooks.Add
sfilename = state & ".xlsx"
'Set the Location
ActiveWorkbook.SaveAs ThisWorkbook.Path & "\" & sfilename
Application.DisplayAlerts = False
ws.Activate
rData.AutoFilter Field:=6, Criteria1:=state
rData.Copy
Windows(state).Activate
ActiveSheet.Paste
ActiveWorkbook.Close SaveChanges:=True
Next rfl
Application.DisplayAlerts = True
End With
ws.Columns(Columns.Count).ClearContents
rData.AutoFilter
End Sub
Hi I downloaded an excel file with macros that generates pdf files according to a list. There are 2 sheets and the pdf are generated from the sheet called "WEST" to generate them it uses an Autofilter function in column D so it generates a pdf for each unique value specified in the list from the sheet called "PRACTICE".
Here is the link to the file http://nhsexcel.com/filtered-list-to-pdf/
The thing is that I want to add exceptions to the code, for example I don´t want to generate pdf´s of the rows in the sheet "WEST", that contain in column i values less than 10.
I tried to add an autofilter with that criteria but the code keeps saying that it´s not a valid metod.
Sub PracticeToPDF()
'Prepared by Dr Moxie
Dim ws As Worksheet
Dim ws_unique As Worksheet
Dim DataRange As Range
Dim iLastRow As Long
Dim iLastRow_unique As Long
Dim UniqueRng As Range
Dim Cell As Range
Dim LastRow As Long
Dim LastColumn As Long
Application.ScreenUpdating = False
'Note that the macro will save the pdf files in this active directory so you should save in an appropriate folder
DirectoryLocation = ActiveWorkbook.Path
Set ws = Worksheets("WEST") 'Amend to reflect the sheet you wish to work with
Set ws_unique = Worksheets("PRACTICE") 'Amend to reflect the sheet you wish to work with
'Find the last row in each worksheet
iLastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
iLastRow_unique = ws_unique.Cells(Rows.Count, "A").End(xlUp).Row
With ws
'I've set my range to reflect my headers which are fixed for this report
Set DataRange = ws.Range("$A$8:$L$" & iLastRow)
'autofilter field is 4 as I want to print based on the practice value in column D
DataRange.AutoFilter Field:=4
Set UniqueRng = ws_unique.Range("A4:A" & iLastRow_unique)
For Each Cell In UniqueRng
DataRange.AutoFilter Field:=4, Criteria1:=Cell
Name = DirectoryLocation & "\" & Cell.Value & " Practice Report" & ".pdf"
ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Name _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
Next Cell
End With
With ws
.Protect Userinterfaceonly:=True, _
DrawingObjects:=False, Contents:=True, Scenarios:= _
True, AllowFormattingColumns:=True, AllowFormattingRows:=True
.EnableOutlining = True
.EnableAutoFilter = True
If .FilterMode Then
.ShowAllData
End If
End With
Application.ScreenUpdating = True
End Sub
I would like to just generate the pdf files of all the rows which value in column I is greater than ten, but no matter what I have tried it keeps either generating all the pdfs or not generating any at all.
I think you want an IF statement to check if there are any rows visible (excluding headers) before proceeding with the export.
That's what I do in the code below.
Option Explicit
Sub PracticeToPDF()
Dim dataSheet As Worksheet
Set dataSheet = Worksheets("WEST") 'Amend to reflect the sheet you wish to work with
Dim uniqueSheet As Worksheet
Set uniqueSheet = Worksheets("PRACTICE") 'Amend to reflect the sheet you wish to work with
'Note that the macro will save the pdf files in this active directory so you should save in an appropriate folder
Dim directoryLocation As String
directoryLocation = ActiveWorkbook.Path ' Maybe you should be using Thisworkbook.Path?
If Len(Dir$(directoryLocation, vbDirectory)) = 0 Then ' Just in case the ActiveWorkbook hasn't been saved.
MsgBox "'" & directoryLocation & "' is not a valid path. Code will stop running now."
Exit Sub
End If
'Find the last row in each worksheet
Dim lastRowOnDataSheet As Long
lastRowOnDataSheet = dataSheet.Cells(dataSheet.Rows.Count, "A").End(xlUp).Row
Dim lastRowOnUniqueSheet As Long
lastRowOnUniqueSheet = uniqueSheet.Cells(uniqueSheet.Rows.Count, "A").End(xlUp).Row
'I've set my range to reflect my headers which are fixed for this report
Dim dataRange As Range
Set dataRange = dataSheet.Range("$A$8:$L$" & lastRowOnDataSheet)
Dim uniqueRange As Range
Set uniqueRange = uniqueSheet.Range("A4:A" & lastRowOnUniqueSheet)
'Application.ScreenUpdating = False ' Uncomment this when the code is working.
If dataSheet.AutoFilterMode Then
On Error Resume Next
dataSheet.ShowAllData ' Will throw if filters have already been cleared
On Error GoTo 0
End If
Dim cell As Range
For Each cell In uniqueRange
With dataRange
.AutoFilter Field:=4, Criteria1:=cell ' Filter for whatever unique value we're currently at in the loop
.AutoFilter Field:=9, Criteria1:=">10" ' Filter column I for values greater than 10
' Only export the PDF if the filter leaves at least one row (not including the header row)
If .Columns(1).SpecialCells(xlCellTypeVisible).CountLarge > 1 Then
Dim fullPathToExportPDFTo As String
fullPathToExportPDFTo = directoryLocation & "\" & cell.Value & " Practice Report" & ".pdf"
dataSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fullPathToExportPDFTo, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
.Parent.ShowAllData ' Reset the filter for the loop iteration.
End With
Next cell
With dataSheet
.Protect Userinterfaceonly:=True, DrawingObjects:=False, Contents:=True, Scenarios:=True, _
AllowFormattingColumns:=True, AllowFormattingRows:=True
.EnableOutlining = True
.EnableAutoFilter = True
End With
' Application.ScreenUpdating = True ' Uncomment this when the code is working.
End Sub
I am struggling with my VBA code. Instead of fixed values in a table, which contains the names how the workbooks should be saved as. My range needs to be variable (below example for starting with range "A3").
Sheets("CC").Select 'sheet with the names
Range("A3").Select ' starting from this range are the names in a column
Selection.Copy
Sheets("CZK").Select 'going to different sheet to paste some value
Range("B2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False 'pasting values to different sheet
Application.CutCopyMode = False
Sheets("CC").Select 'returning back to the sheet with names
Nazev = Range("A3")
ActiveWorkbook.SaveAs Filename:=cesta & Nazev 'saving it with predefined path and name
I have to start like this:
Set MyRange = Sheets("CC").Range("A3") ' predefining varible range
Set MyRange = Range(MyRange, MyRange.End(xlDown))
But then I am stuck.
Something like this should work for you:
Sub tst()
Dim wb As Workbook
Dim wsNames As Worksheet
Dim wsDest As Worksheet
Dim NameCells As Range
Dim NameCell As Range
Dim cesta As String
Dim Nazev As String
cesta = "C:\Test\"
Set wb = ActiveWorkbook
Set wsNames = wb.Sheets("CC")
Set wsDest = wb.Sheets("CZK")
Set NameCells = wsNames.Range("A3", wsNames.Cells(wsNames.Rows.Count, "A").End(xlUp))
Application.DisplayAlerts = False
For Each NameCell In NameCells
Nazev = NameCell.Value
wsDest.Range("B2").Value = Nazev
wb.SaveAs cesta & Nazev & ".xlsm", xlOpenXMLWorkbookMacroEnabled
Next NameCell
Application.DisplayAlerts = True
End Sub