I created this code that's meant to pull a specific report that's been saved in a folder clean up (delete) the data and add new titles, divide the information up by one of the fields, then copy the info to a new sheet with the name of the sheet being that field on a scalable and variable basis. The report can vary from being 10x20 to being 900x20 depending, and the field itself is a constantly changing value (it's people at a company, turnover happens).
I've removed some of the more sensitive information. As a note, I'm trying to use a lot of what was told to me in a previous question by @Mat'sMug, so if there's any practices I'm missing, please let me know.
Option Explicit
Function SheetExists(sheetName As String, Optional Workbook As Workbook) As Boolean
Dim sheet As Worksheet
' Checks if the workbook name exists in existing sheets.
If Workbook Is Nothing Then Set Workbook = ThisWorkbook
On Error Resume Next
Set sheet = Workbook.Sheets(sheetName)
On Error GoTo 0
SheetExists = Not sheet Is Nothing
End Function
Sub PO_Create()
' Initializes variables.
Dim lastRow As Integer
Dim lastCol As Integer
Dim weekStart As String
Dim dirFile As String
Dim terrName As String
Dim passProc As String
Dim wbClear As Object
Dim titleCol As Integer
Dim terrRow As Integer
Dim headers As Range
Dim dataRow As Integer
Dim newLine As Integer
Dim fileSave As String
Dim Infobox As Object
' Asks for the password to run the macro.
passProc = InputBox("Please enter the password to refresh the report.", _
"Password Protected")
If passProc <> "Analyst!" Then
MsgBox "Invalid password.", vbOKOnly
Exit Sub
End If
' Turn off the screen and checks if the related file exists.
Application.ScreenUpdating = False
weekStart = Format(Admin.Cells(2, 3).Value, "mm-dd-yyyy")
dirFile = "C:\FileLocation " & _
weekStart & ".xls"
If Dir(dirFile) = "" Then
MsgBox "That file date was not found, please try a different date or rerun the report.", vbOKOnly
Exit Sub
End If
Application.DisplayAlerts = False
' Clears all old data and sheets.
POList.Cells.ClearContents
For Each wbClear In ThisWorkbook.Worksheets
If wbClear.Name <> "PO List" And wbClear.Name <> "Administration" Then
wbClear.Delete
End If
Next wbClear
Application.DisplayAlerts = True
' Opens the related workbook and trims unnecessary data.
Workbooks.Open (dirFile)
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
For titleCol = lastCol To 1 Step -1
If Cells(1, titleCol).Value <> "1" And _
Cells(1, titleCol).Value <> "2" And _
Cells(1, titleCol).Value <> "3" And _
Cells(1, titleCol).Value <> "4" And _
Cells(1, titleCol).Value <> "5" And _
Cells(1, titleCol).Value <> "6" And _
Cells(1, titleCol).Value <> "7" And _
Cells(1, titleCol).Value <> "8" And _
Cells(1, titleCol).Value <> "9" And _
Cells(1, titleCol).Value <> "10" Then
Columns(titleCol).EntireColumn.Delete
End If
Next titleCol
' Reinitializes the last cells.
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
' Copies and pastes the PO list information to the workbook.
ActiveSheet.Range(Cells(1, 1), Cells(lastRow, lastCol)).Copy
ThisWorkbook.Sheets("PO List").Activate
Cells(1, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Application.CutCopyMode = False
POList.Range(Cells(1, 8), Cells(lastRow, 9)).Cut
Range(Cells(1, 1), Cells(lastRow, 2)).Insert (xlToRight)
Application.CutCopyMode = False
Selection.Columns.AutoFit
' Closes the PO list and focuses the window on the Report runner.
Workbooks("po list " & weekStart & ".xls").Activate
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
ThisWorkbook.Activate
' Renames column names.
Cells(1, 1).Value = "Territory"
Cells(1, 2).Value = "Name"
Cells(1, 3).Value = "PO Number"
Cells(1, 4).Value = "Vendor"
Cells(1, 5).Value = "Buyer"
Cells(1, 6).Value = "Order Date"
Cells(1, 7).Value = "Request Date"
Cells(1, 8).Value = "Job Number"
Cells(1, 9).Value = "Job Name"
Cells(1, 10).Value = "Job Task"
' Reinitializes the last cells.
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
' Converts the numbers stored as text to numbers.
POList.Columns("A:A").Insert (xlShiftToRight)
For terrRow = 2 To lastRow
Cells(terrRow, 1).Value = "=B" & terrRow & "*1"
Next terrRow
Range(Cells(2, 1), Cells(lastRow, 1)).Copy
Cells(2, 2).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Cells(1, 1).EntireColumn.Delete (xlShiftToLeft)
' Reinitializes the last cells.
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
' Loops through each line and sorts it to either a new sheet, or to an existing sheet.
Set headers = POList.Range(Cells(1, 1), Cells(1, lastCol))
For dataRow = 2 To lastRow
terrName = Format(POList.Cells(dataRow, 1).Value)
If SheetExists(terrName) Then
' Go to the end of that sheet and copy/paste the information.
POList.Select
Range(Cells(dataRow, 1), Cells(dataRow, lastCol)).Copy
Sheets(terrName).Select
newLine = Cells(Rows.Count, 1).End(xlUp).Row + 1
Cells(newLine, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Columns.AutoFit
POList.Select
Else
' Create a new sheet, add headers, and copy the line.
Sheets.Add.Name = terrName
ActiveSheet.Tab.Color = 108
headers.Copy
Sheets(terrName).Select
Cells(1, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
POList.Select
Range(Cells(dataRow, 1), Cells(dataRow, lastCol)).Copy
Sheets(terrName).Select
newLine = Cells(Rows.Count, 1).End(xlUp).Row + 1
Cells(newLine, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Columns.AutoFit
POList.Select
End If
Next dataRow
' Save the worksheet with a new name and resets the workbook display properties.
Application.DisplayAlerts = False
fileSave = "C:\NewFileLocation " & _
weekStart & " to " & Format(Admin.Cells(2, 3).Value + 4, "mm-dd-yyyy") & ".xlsm"
ThisWorkbook.SaveAs (fileSave)
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Exit Sub
' This is where the code will go if an error occurs
Errhandler:
Set Infobox = CreateObject("Wscript.Shell")
Select Case Infobox.Popup( _
"The code has encountered an error and needs to close." & _
vbCrLf & vbCrLf & "Please contact the Financial Analyst with the error"
& vbCrLf & _
"below." & vbCrLf & vbCrLf & _
"Number: #" & Err.Number & vbCrLf & _
"Error Description: " & vbCrLf & Err.Description & vbCrLf & vbCrLf & _
"Press OK or wait 5 seconds to close this.", 5, "Error!", 1)
Case 1, -1
Exit Sub
End Select
End Sub
Is there a better way to do this that still allows for expansion?
_
underscore is causing your code not to compile. It's after the part ` ... Financial Analyst with the error"` \$\endgroup\$