Space check previous page and insert rows there Excel - vba

I have block of text in (A795:O830). It is separated from other pages by Page Break and is always the last page of printed (xls, pdf) document. Sometimes there are a lot of free space on first pages and (A795:O830) could have fitted there. Now it is done by Page Break and is not changeble. In my situation 66 rows can fit on one page.
Is there any macro that can automatically check if there is enough empty space on previous page to fit (A795:O830) and insert it there?
Here is my current macro:
Sub Remove_color()
Dim myRange As Range
Dim cell As Range
Set myRange = Range("A24:O785")
For Each cell In myRange
myRange.Interior.ColorIndex = 0
Next
End Sub
Sub Hide_empty_cells()
Set rr = Range("A24:N832")
For Each cell In rr
cell.Select
If cell.HasFormula = True And cell.Value = "" And cell.EntireRow.Hidden = False Then Rows(cell.Row).EntireRow.Hidden = True
Next cell
End Sub
Sub Save_excel()
Dim iFileName$, iRow&, iCol&, iCell As Range, iArr
iFileName = ThisWorkbook.Path & "\New_folder_" & [D5] & "_" & ".xls"
iArr = Array(1, 3, 4): iCol = UBound(iArr) + 1
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlManual
ThisWorkbook.Sheets(2).Copy
With ActiveWorkbook.ActiveSheet
.Buttons.Delete '.Shapes("Button 1").Delete
.UsedRange.Value = .UsedRange.Value
.SaveAs iFileName, xlExcel8: .Parent.Close
End With
Application.Calculation = xlAutomatic
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Sub Save_pdf()
ActiveWorkbook.Sheets(2).Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\New_folder_\" & [D5] & "_" & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=No, _
OpenAfterPublish:=False
End Sub
Sub doitallplease()
Call Remove_color
Call Hide_empty_cells
Call Save_excel
Call Save_pdf
End Sub

Related

Excel VBA: Split data into multiple worksheets based on row and condition

I have master list, which I want to divide into separate worksheets based on Job Role. In addition, only courses marked with an "X" should appear in the individual worksheet. See image of master list below
IMAGE
Basing off my code from this sample, but to no avail (error I had was unable to get the Match property of WorksheetFunction class): https://www.extendoffice.com/documents/excel/1174-excel-split-data-into-multiple-worksheets-based-on-column.html
Sub parse_data()
Dim lr As Long
Dim ws As Worksheet
Dim vrow, i As Integer
Dim irow As Long
Dim myarr As Variant
Dim title As String
Dim titlerow As Integer
vrow = 6
Set ws = ActiveSheet
lr = ws.Cells(vrow, ws.Columns.Count).End(xlToLeft).Column
irow = ws.Rows.Count
For i = 7 To lr
If ws.Cells(vrow, i) <> " " And Application.WorksheetFunction.Match(ws.Cells(vrow, i), ws.Rows(irow), 0) = 0 Then
ws.Cells(irow, ws.Columns.Count).End(xlUp).Offset(1) = ws.Cells(vrow, i)
End If
Next
myarr = Application.WorksheetFunction.Transpose(ws.Rows(irow).SpecialCells(xlCellTypeConstants))
ws.Rows(irow).Clear
For i = 2 To UBound(myarr)
ws.Range(title).AutoFilter field:=vrow, Criteria1:=myarr(i) & ""
If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
Else
Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
End If
ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
Sheets(myarr(i) & "").Columns.AutoFit
Next
ws.AutoFilterMode = False
ws.Activate
End Sub
I think this should do what you want.
Sub Copy_To_Worksheets()
'Note: This macro use the function LastRow
Dim My_Range As Range
Dim FieldNum As Long
Dim CalcMode As Long
Dim ViewMode As Long
Dim ws2 As Worksheet
Dim Lrow As Long
Dim cell As Range
Dim CCount As Long
Dim WSNew As Worksheet
Dim ErrNum As Long
'Set filter range on ActiveSheet: A1 is the top left cell of your filter range
'and the header of the first column, D is the last column in the filter range.
'You can also add the sheet name to the code like this :
'Worksheets("Sheet1").Range("A1:D" & LastRow(Worksheets("Sheet1")))
'No need that the sheet is active then when you run the macro when you use this.
Set My_Range = Range("A1:D" & 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 worksheet"
Exit Sub
End If
'This example filters on the first column in the range(change the field if needed)
'In this case the range starts in A so Field:=1 is column A, 2 = column B, ......
FieldNum = 1
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
'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
'Add a worksheet to copy the a unique list and add the CriteriaRange
Set ws2 = Worksheets.Add
With ws2
'first we copy the Unique data from the filter field to ws2
My_Range.Columns(FieldNum).AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=.Range("A1"), 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("A2: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 a new worksheet
Set WSNew = Worksheets.Add(After:=Sheets(Sheets.Count))
On Error Resume Next
WSNew.Name = cell.Value
If Err.Number > 0 Then
ErrNum = ErrNum + 1
WSNew.Name = "Error_" & Format(ErrNum, "0000")
Err.Clear
End If
On Error GoTo 0
'Copy the visible data to the new worksheet
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
End If
'Show all data in the range
My_Range.AutoFilter Field:=FieldNum
Next cell
'Delete the ws2 sheet
On Error Resume Next
Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True
On Error GoTo 0
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
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
Here is the link:
https://www.rondebruin.nl/win/s3/win006_4.htm
Or, this.
Sub Copy_To_Workbooks()
'Note: This macro use the function LastRow
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 filter range on ActiveSheet: A1 is the top left cell of your filter range
'and the header of the first column, D is the last column in the filter range.
'You can also add the sheet name to the code like this :
'Worksheets("Sheet1").Range("A1:D" & LastRow(Worksheets("Sheet1")))
'No need that the sheet is active then when you run the macro when you use this.
Set My_Range = Range("A1:D" & 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
'This example filters on the first column in the range(change the field if needed)
'In this case the range starts in A so Field:=1 is column A, 2 = column B, ......
FieldNum = 1
'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
'you can use also this "C:\Users\Ron\test"
MyPath = Application.DefaultFilePath
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'Create folder for the new files
foldername = MyPath & Format(Now, "yyyy-mm-dd hh-mm-ss") & "\"
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
https://www.rondebruin.nl/win/s3/win006_3.htm

Split excel file tabs into individual files

I would like to split my workbooks, and have each sheet save as it's own file. I don't mind if the sheets save to the same folder that the original workbook is in. I also want to keep the original workbook intact. Here is the code I've been working with.
Sub Splitbook()
Dim xPath As String
xPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xWs.Name & ".xls"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
This has been working okay, but breaks when I try to use it on some of my larger workbooks. Not sure why. Could anyone help me refine this so I don't run into issues. Thanks!
Please try it this way.
Sub Copy_To_Workbooks()
'Note: This macro use the function LastRow
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 filter range on ActiveSheet: A1 is the top left cell of your filter range
'and the header of the first column, D is the last column in the filter range.
'You can also add the sheet name to the code like this :
'Worksheets("Sheet1").Range("A1:D" & LastRow(Worksheets("Sheet1")))
'No need that the sheet is active then when you run the macro when you use this.
Set My_Range = Range("A1:D" & 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
'This example filters on the first column in the range(change the field if needed)
'In this case the range starts in A so Field:=1 is column A, 2 = column B, ......
FieldNum = 1
'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
'you can use also this "C:\Users\Ron\test"
MyPath = Application.DefaultFilePath
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'Create folder for the new files
foldername = MyPath & Format(Now, "yyyy-mm-dd hh-mm-ss") & "\"
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
From this site.
http://www.rondebruin.nl/win/s3/win006_3.htm

Export sheet as CSV, add new column with header and insert workbook name in all the cells

I want to create a macro that copies a sheet called "Week" from my workbook, deletes the first row, adds a new column (farthest to the left), assigns it the header "Department" and assigns it a fixed value. The fixed value should be the name of the CSV file. The name can be found on the front page in cell G6. I don't want the fixed value to be copied all the way down in the first column. I want it to be copied until there isn't any value in any of the columns to the right of the first column. Currently I've tried just comparing it to the second column (column B). I get the message:
Run-time error '424':
Object required
and is referring back to:¨
If InStr(1, thiswork.Sheets(ActiveSheet.Name).Range("$B$" & X), "") > 0 Then
This is my code:
Sub Export_pb_uge()
Dim MyPath As String
Dim MyFileName As String
MyPath = "C:mypath1"
MyFileName = Sheets("Front_Page").Range("g6").Value
Application.ScreenUpdating = False
Application.DisplayAlerts = False
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Sheets("PB_uge").Visible = True
Sheets("PB_uge").Copy
Rows(1).EntireRow.Delete
With target_sheet
Range("A1").EntireColumn.Insert
Range("A1").Value = "Department"
End With
If ThisWorkbook.Sheets(ActiveSheet.Name).FilterMode Then ThisWorkbook.Sheets(ActiveSheet.Name).ShowAllData
lRow = ThisWorkbook.Sheets(ActiveSheet.Name).Cells(Rows.Count, "B").End(xlUp).Row
For X = 1 To lRow
If InStr(1, thiswork.Sheets(ActiveSheet.Name).Range("$B$" & X), "") > 0 Then
target_sheet.Range("$A$" & X) = ActiveSheet.Name
End If
Next
With ActiveWorkbook
.SaveAs Filename:= _
MyPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False, _
Local:=True
.Close False
End With
Sheets("Week").Visible = False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Well spotted gazzz0x2z, however I would also declare and set target_sheet
Dim target_sheet As Worksheet
Set target_sheet = ActiveSheet ' or for example Sheets("sheet1")
With target_sheet
Range("A1").EntireColumn.Insert
Range("A1").Value = "Department"
End With
If ThisWorkbook.Sheets(ActiveSheet.Name).FilterMode Then ThisWorkbook.Sheets (ActiveSheet.Name).ShowAllData
lRow = ThisWorkbook.Sheets(ActiveSheet.Name).Cells(Rows.Count, "B").End(xlUp).Row
For X = 1 To lRow
If InStr(1, ThisWorkbook.Sheets(ActiveSheet.Name).Range("$B$" & X), "") > 0 Then
target_sheet.Range("$A$" & X) = ActiveSheet.Name
End If
Next
Try :
If InStr(1, ThisWorkbook.Sheets(ActiveSheet.Name).Range("$B$" & X), "") > 0 Then
Seems like, for some reason, you've lost 4 letters.
I found the answer to be:
Sub Export_PB_uge()
Dim pb_uge As Worksheet
Dim myPath As String
Dim MyFileName As String
Dim x As Long
Dim wsCSV As Worksheet
myPath = "C:mypath1"
MyFileName = Sheets("Front_Page").Range("g6").Value
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
If Not Right(myPath, 1) = "\" Then myPath = myPath & "\"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
With ThisWorkbook.Sheets("PB_uge")
If .FilterMode Then pb_uge.ShowAllData
.Visible = True
.Copy
End With
Set wsCSV = ActiveWorkbook.Sheets(1)
With wsCSV
.Range("A1").EntireRow.Delete
.Range("A1").EntireColumn.Insert
.Range("A1").Value = "Department"
lRow = .Cells(Rows.Count, "C").End(xlUp).Row
.Range("A2:A" & lRow) = ThisWorkbook.Sheets("Front_Page").Range("g6").Value
.Parent.SaveAs Filename:= _
myPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False, _
Local:=True
.Parent.Close False
End With
ThisWorkbook.Sheets("PB_uge").Visible = False
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "CSV saved at " & myPath & MyFileName, vbInformation
End Sub

If cell value is 0 then delete column, Excel VBA - deletes all columns

I'm trying to delete columns if a certain cell in that column is "0" - I'm looping through all worksheets. I've tried different variations and it all ends up with different results - either nothing is deleted or everything is deleted.
Whole code:
Sub Finalize()
Dim finalform As Worksheet
Dim deletename As String
Dim finalworkbook As Workbook
Dim ws As Worksheet
Dim copyrange As Range
Dim columnloop As Range
Dim finalarray As Variant
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set finalform = Workbooks(ActiveWorkbook.Name).ActiveSheet
finalarray = Array(finalform.Range("D3").Value, finalform.Range("D4").Value, finalform.Range("D5").Value _
, finalform.Range("D6").Value, finalform.Range("D7").Value, finalform.Range("D8").Value, finalform.Range("D9").Value _
, finalform.Range("D10").Value, finalform.Range("D11").Value, finalform.Range("D12").Value, finalform.Range("D13").Value _
, finalform.Range("D14").Value, finalform.Range("D15").Value)
On Error Resume Next
For a = 3 To 20
If Range("B" & a).Value <> "" Then
Workbooks.Open finalform.Range("B" & a).Value
Set finalworkbook = Workbooks(ActiveWorkbook.Name)
'Find, replace, remove
For Each ws In finalworkbook.Worksheets
'Copy paste values
If Not IsInArray(ws.Name, finalarray) Then
Set copyrange = ws.Cells
copyrange.Copy
copyrange.PasteSpecial xlPasteValues
End If
Application.CutCopyMode = False
Next ws
For Each ws In finalworkbook.Worksheets
'Delete sheets
For b = 3 To 15
deletename = finalform.Range("D" & b).Value
If deletename <> "" Then
finalworkbook.Worksheets(deletename).Delete
End If
Next b
With ws
myChar = Chr(10)
'Enter space
.UsedRange.Replace What:="~~", Replacement:=myChar, LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
For c = .UsedRange.Columns.Count To 1 Step -1
cName = Split(Cells(, c).Address, "$")(1)
nom = .Range(cName & "8").Value
If nom = 0 Then
.Columns(c).EntireColumn.Delete
End If
Next c
End With
Next ws
finalworkbook.Save
finalworkbook.Close
End If
Next a
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
The issue here is how VBA interprets the =0 operation. Here is a quick list. You most likely want to use IsEmpty() as ZygD noted.
IsEmpty(cell.Value) 'Returns true if the cell is empty, or false if it is filled with 0.
cell.Value = 0 'Returns true if the cell is empty and if it is filled with 0, false otherwise.
IsNumeric(cell.Value) 'Returns true if the cell is empty, or if it is filled with any number, false otherwise.
If you're looping through all worksheets, you can even use vbNullStringinstead of 0 or "", as this runs faster.

VBA Inputbox Filter enhancements

the code below works fine. However, when a user doesn't include anything in the InputBox or clicks on the 'Close' button or inputs a value which doesn't exist I want it to display a msgbox stating the reason and delete sheets 'PreTotal'.
Is there a better way to handle user input? Need some help here on how to go about it. Thank you.
Sub Filterme()
Dim wSheetStart As Worksheet
Dim rFilterHeads As Range
Dim strCriteria As String
Set wSheetStart = ActiveSheet
Set rFilterHeads = Range("M1", Range("M1").End(xlToLeft))
With wSheetStart
.AutoFilterMode = False
rFilterHeads.AutoFilter
strCriteria = InputBox("Enter Date - MMDDYY")
If strCriteria = vbNullString Then Exit Sub
rFilterHeads.AutoFilter Field:=13, Criteria1:="=*" & strCriteria & "*"
End With
Worksheets("PreTotal").UsedRange.Copy
Sheets.Add.Name = "Total"
Worksheets("Total").Range("A1").PasteSpecial
End Sub
Is this what you are trying?
Change
If strCriteria = vbNullString Then Exit Sub
to
If strCriteria = vbNullString Then
MsgBox "You choose not to continue"
Application.DisplayAlerts = False
Worksheets("PreTotal").Delete
Application.DisplayAlerts = True
Exit Sub
End If
FOLLOWUP
Thanks #Rout - This worked. One more thing what if the input criteria does not exist in the sheet? How should I tackle that? – user823911 11 mins ago
Is this what you are trying? Also if you are filtering the range based on Col M (1st Col in the range) then change the line
rFilterHeads.AutoFilter Field:=13, Criteria1:="=*" & strCriteria & "*"
to
rFilterHeads.AutoFilter Field:=1, Criteria1:="=*" & strCriteria & "*"
CODE
Sub Filterme()
Dim wSheetStart As Worksheet
Dim rFilterHeads As Range, aCell As Range
Dim strCriteria As String
Set wSheetStart = ActiveSheet
Set rFilterHeads = Range("M1", Range("M1").End(xlToLeft))
With wSheetStart
.AutoFilterMode = False
strCriteria = InputBox("Enter Date - MMDDYY")
If strCriteria = vbNullString Then
MsgBox "You choose not to continue"
Application.DisplayAlerts = False
Worksheets("PreTotal").Delete
Application.DisplayAlerts = True
Exit Sub
End If
Set aCell = .Columns(13).Find(What:=strCriteria, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
MsgBox "Search Criteria Not Found"
Exit Sub
End If
rFilterHeads.AutoFilter
rFilterHeads.AutoFilter Field:=13, Criteria1:="=*" & strCriteria & "*"
Sheets.Add.Name = "Total"
Worksheets("PreTotal").UsedRange.Copy
Worksheets("Total").Range("A1").PasteSpecial
End With
End Sub