Macro breaks when ran for the first time of the day - excel

When I run my macro for the first time for the day it fails when it adds another sheet to the file.
Run-time error 1004: That name is already taken. Try a different
one.
My goal:
look for the file within \Downloads
convert the saved file it found from .xls -> .xlsx
delete the original downloaded file
run a bunch of formatting for printing.
When it fails, I close the current file, re-download the file, manually save the file with the needed format & name, delete the download, re-download the file.
After that I can run the macro.
The line that breaks: Sheets.Add(After:=Sheets("Dock Activity Report")).Name = "Cases"
Sub Schedule_macro()
Dim Filename, Pathname, SaveFileName As String
Dim wb As Workbook
Dim UserName As String
UserName = Environ("username")
Pathname = "C:\Users\" & Environ$("username") & "\Downloads\"
Filename = Dir(Pathname & "Dock_Activity_*.xls")
SaveFileName = Dir(Pathname & "dockactivity.xlsx")
Application.DisplayAlerts = False
If Len(Dir(Pathname & "Dock_Activity_*.xls")) > 0 Then
Debug.Print "Filename found, running macro"
Else
MsgBox "You need to download the" & vbNewLine & "Dock Activity Report from the" & vbNewLine & "'Report Run Log' in Lean." & vbNewLine & vbNewLine & "Once downloaded, please rerun the macro", vbCritical, "HiRise Schedule Macro"
Debug.Print "could not find Filename within given Pathname"
Debug.Print "exiting macro"
Exit Sub
End If
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
wb.CheckCompatibility = True
Application.DisplayAlerts = False
wb.SaveAs Filename:="dockactivity", FileFormat:=xlOpenXMLWorkbook
wb.Close SaveChanges:=False
Filename = Dir(Pathname & "Dock_Activity_*.xls")
Filename = Dir()
Loop
Application.DisplayAlerts = True
If Dir(Pathname & "Dock_Activity_*.xls") <> "" Then
kill (Pathname & "Dock_Activity_*.xls")
End If
Debug.Print "looking for SaveFileName within given Pathname"
Set wb = Workbooks.Open(Pathname & "dockactivity.xlsx")
Debug.Print "SaveFileName found, opening file"
Windows("dockactivity.xlsx").Activate
Rows("1:21").Delete Shift:=xlUp
Range("A:B,D:F,H:N,S:S,U:V,X:Y,AB:AK,AM:BA").Delete Shift:=xlToLeft
Columns("H:H").Cut
Columns("A:A").Insert Shift:=xlToRight
Columns("K:K").Cut
Columns("G:G").Insert Shift:=xlToRight
Columns("J:K").Copy
Range("L1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Columns("J:K").ClearContents
Range("J1").FormulaR1C1 = "Trailer Number"
Range("K1").FormulaR1C1 = "Arrival Time"
Columns("G:M").Copy
Range("N1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.ClearContents
Range("N1").FormulaR1C1 = "Door"
Range("O1").FormulaR1C1 = "Ship Rail"
Range("P1").FormulaR1C1 = "Staged"
Range("Q1").FormulaR1C1 = "Check If Loaded"
Range("R1").FormulaR1C1 = "Case Picks"
Range("S1").FormulaR1C1 = "Layer Picks"
Range("T1").FormulaR1C1 = "Check if Released by Pool"
Debug.Print "1:1 table headers complete"
Columns("A:B").ColumnWidth = 17.71
Columns("C:C").ColumnWidth = 19.14
Columns("D:D").ColumnWidth = 25.71
Columns("E:E").ColumnWidth = 14.41
Columns("F:F").ColumnWidth = 10.71
Columns("G:G").ColumnWidth = 30.29
Columns("H:H").ColumnWidth = 9.43
Columns("I:I").ColumnWidth = 13.71
Columns("J:J").ColumnWidth = 26.14
Columns("K:L").ColumnWidth = 23.57
Columns("M:M").ColumnWidth = 46
Columns("N:S").ColumnWidth = 15
Columns("T:T").ColumnWidth = 12.86
Debug.Print "column resizing complete"
Cells.Select
With Selection.Font
.Name = "Arial"
.Size = 14
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
Rows("1:1").RowHeight = 75
Rows("2:150").RowHeight = 55
' #############################################################################
Sheets.Add(After:=Sheets("Dock Activity Report")).Name = "Cases"
Sheets.Add(After:=Sheets("Cases")).Name = "Layers"
' #############################################################################
Sheets("Dock Activity Report").Range("R2:R150").FormulaR1C1 = "=VLOOKUP(RC[-17],Cases!C[-13]:C[-12],2,FALSE)"
Sheets("Dock Activity Report").Range("S2:S150").FormulaR1C1 = "=VLOOKUP(RC[-18],Layers!C[-15]:C[-14],2,FALSE)"
Worksheets("Dock Activity Report").Select
Range("A2:T150").Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$C2=""Live Trailer"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
End With
Range("B2:B150").Select
ActiveWorkbook.Worksheets("Dock Activity Report").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Dock Activity Report").Sort.SortFields.Add Key:= _
Range("B2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Dock Activity Report").Sort
.SetRange Range("A1:T150")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ActiveWorkbook.Worksheets("Dock Activity Report").Select
Columns("A:A").Copy
Columns("B:B").Insert Shift:=xlToRight
Range("B2").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=IFERROR(RC[-1]*1,TRIM(RC[-1]))"
Range("B3").Select
Range("B2").Select
Selection.AutoFill Destination:=Range("B2:B150"), Type:=xlFillDefault
Range("B2:B150").Select
Columns("B:B").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("B:B").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Debug.Print "A:A value reformat complete"
Sheets("Dock Activity Report").Select
Columns("A:T").Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=COUNTA($A1:$F1)>0"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Borders
.LineStyle = xlContinuous
.TintAndShade = 0
.Weight = xlThin
End With
Selection.FormatConditions(1).StopIfTrue = False
Debug.Print "cell borders added"
Dim r As Long
Dim LastRow As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
For r = LastRow To 1 Step -1
If Cells(r, 1) = 0 Then
Rows(r).Delete
End If
Next r
Range("A1").Select
Sheets("Cases").Range("E2:E300").FormulaR1C1 = "=VALUE(TRIM(CLEAN(RC[-4])))"
Sheets("Cases").Range("F2:F300").FormulaR1C1 = "=RC[-2]"
Sheets("Cases").Columns("E:F").EntireColumn.Hidden = True
Sheets("Layers").Range("D2:D300").FormulaR1C1 = "=VALUE(TRIM(CLEAN(RC[-3])))"
Sheets("Layers").Range("E2:E300").FormulaR1C1 = "=RC[-2]"
Sheets("Layers").Columns("D:E").EntireColumn.Hidden = True
Sheets("Dock Activity Report").Range("A1").Select
Application.DisplayAlerts = False
ActiveWorkbook.Save
Application.DisplayAlerts = True
MsgBox "All Finished!", vbInformation, "HiRise Schedule"
ActiveWorkbook.Save
End Sub

That is because there is already a sheet with that name.
Add this code and it will be ok.
On Error Resume Next
Application.DisplayAlerts = False
Sheets("Cases").Delete
Application.DisplayAlerts = True
On Error GoTo 0
Sheets.Add(After:=Sheets("Dock Activity Report")).Name = "Cases"
TIP: Avoid the use of .Select/Activate. Work with Objects. You may want to see How to avoid using Select in Excel VBA. It will be easy to manage the code as well.

Related

Intermittent Run-time Error 1004 or 13 in Excel 365

I am at a loss, I have been working to create this macro to help automate an obnoxious process we have at work and the best way to sum up where it is right now is, 60% of the time it works every time!
The macro takes a workbook with the raw data, reorders the columns, filters out data based on certain criteria, creates separate files for each unique value in one of the columns and then attaches that newly created workbook to an email. The email has text and a logo that is placed into the body of the email. Altogether, when the macro finishes running, it will create anywhere from 7 to 11 separate files and emails.
The problem I am having is when I run the macro, 1 of the following 3 things happens:
No issue, it runs perfectly as expected
I get Run-time error '1004':
Method 'SaveAs' of object '_Workbook' failed
This error happens on this line in the code:
ActiveWorkbook.SaveAs FName
I get Run-time error '13':
Type mismatch
This error happens on this line in the code:
OutMailDocument.Range(0, 1).InsertBefore EmailText
I have tried searching several sites and although I can find information about the errors, I can't seem to find anything that has provided any help in fixing the problem.
I do not know where in my macro I went wrong, but I don't understand why sometimes it works just fine and other times I get one of the 2 errors?
Anyway, I am hoping someone may be able to help provide some guidance as to where I am going wrong. I have posted the full code below for reference:
Sub FeeManagement()
Dim CurrentColumn As Integer
Dim Columnheading As String
Dim lastrow As Long
Dim columnorder As Variant, ndx As Integer
Dim found As Range, counter As Integer
Dim wb As Workbook, ws As Worksheet
Dim lr As Long
Dim i As Integer
Dim ar As Variant
Dim j As Long
Dim rng As Range
Dim OutApp As Object
Dim Outmail As Object
Dim OutMailDocumet As Object
Dim OutShape As Excel.Shape
Dim OutWorksheet As Excel.Worksheet
Dim FName As String
Dim FPath As String
Application.ScreenUpdating = False
ActiveSheet.Cells.Interior.Color = xlNone
Range("A1").End(xlDown).Offset(1).Resize(ActiveSheet.UsedRange.Rows.Count).EntireRow.Delete
ActiveSheet.Cells.Font.Name = "Arial"
ActiveSheet.Cells.Font.Size = "10"
Sheets("Sheet1").Copy before:=Sheets(Sheets.Count)
ActiveSheet.Name = "Original"
Worksheets("Sheet1").Activate
'Remove Unwanted Columns
For CurrentColumn = ActiveSheet.UsedRange.Columns.Count To 1 Step -1
Columnheading = ActiveSheet.UsedRange.Cells(1, CurrentColumn).Value
Select Case Columnheading
Case "Auditor", "Auditor ID", "SAI. Nbr", "Pol. Form", "Pol. Nbr", "Aud. Type", "Days todue date", "Pol. Eff Date", "End Date", "Due Date", "Ins. Name", _
"State", "Market Group", "Scheduled Dt.", "Assigned Date", "CI Date", "Aud. System Key"
Case Else
ActiveSheet.Columns(CurrentColumn).Delete
End Select
Next
'Rearrange Columns
columnorder = Array("Auditor", "Assigned Date", "SAI. Nbr", "Ins Name", "State", "Pol. Eff Date", "End Date", "Due Date", "Pol. Form", "Pol. Nbr", "Days to ue date", _
"MarketGroup", "Aud. Type", "Aud. System Key", "Scheduled DT.", "CI Date", "Auditor ID")
counter = 1
For ndx = LBound(columnorder) To UBound(columnorder)
Set found = Rows("1:1").Find(columnorder(ndx), LookIn:=xlValues, Lookat:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
If Not found Is Nothing Then
If found.Column <> counter Then
found.EntireColumn.Cut
Columns(counter).Insert Shift:=xlToRight
Application.CutCopyMode = False
End If
counter = counter + 1
End If
Next ndx
'Add Due Date Columns and Amend Auditor Column
Range("K1").Value = "Days To Due Date"
Columns("L:L").Insert Shift:=xlToRight, _
CopyOrigin:=xlFormatFromLeftOrAbove
Range("L1").Value = "Days Assigned"
Range("S1").Value = "Sched DT Helper"
Range("T1").Value = "CI Helper"
With Sheets("Sheet1")
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
With .Range("K2:K" & lastrow)
.NumberFormat = "0"
End With
With .Range("L2:L" & lastrow)
.Formula = "=-(B2-Today())"
.NumberFormat = "0"
End With
With .Range("S2:S" & lastrow)
.Formula = "=(Q2-Today())"
.NumberFormat = "0"
End With
With .Range("T2:T" & lastrow)
.Formula = "=ABS(Q2-Today())"
.NumberFormat = "0"
End With
End With
Columns("A:B").Insert Shift:=xlToRight, _
CopyOrigin:=xlFormatFromLeftOrAbove
Range("B1").Value = "Auditor"
With Sheets("Sheet1")
lastrow = .Cells(.Rows.Count, "C").End(xlUp).Row
With .Range("B2:B" & lastrow)
.Formula = "=left(C,25)"
End With
End With
Sheets("Sheet1").Columns("B").Copy
Sheets("Sheet1").Columns("A").PasteSpecial Paste:=xlPasteValues
Columns("B:C").EntireColumn.Delete
Worksheets("Sheet1").Columns("A:Z").AutoFit
Worksheets("Sheet1").Range("A1").AutoFilter
'Filter and Delete records based on assigned/due dates & scheduled DT/CI Dates
Set ws = ActiveSheet
On Error Resume Next
ws.ShowAllData
On Error GoTo 0
ws.Range("A1:A20000").AutoFilter Field:=12, Criteria:="<=6"
Application.DisplayAlerts = False
ws.Range("A2:Z20000").SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ws.ShowAllData
ws.Range("A1:A20000").AutoFilter Field:=11, Criteria:=">=30"
Application.DisplayAlerts = False
ws.Range("A2:Z20000").SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ws.ShowAllData
ws.Range("A1:A20000").AutoFilter Field:=19, Criteria:=">=-3"
Application.DisplayAlerts = False
ws.Range("A2:Z20000").SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ws.ShowAllData
ws.Range("A1:A20000").AutoFilter Field:=20, Criteria:="<=6"
Application.DisplayAlerts = False
ws.Range("A2:Z20000").SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ws.ShowAllData
On Error Resume Next
ws.ShowAllData
On Error GoTo 0
Columns("S:T").EntireColumn.Delete
Columns("P:Q").EntireColumn.Delete
ws.AutoFilter.Sort.SortFields.Clear
ws.AutoFilter.Sort.SortFields.Add2 Key:=Range( _
"K1:K10000"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ws.AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Columns("P:T").Insert Shift:=xlToRight, _
CopyOrigin:=xlFormatFromLeftOrAbove
Range("P1").Value = "New Status"
Range("Q1").Value = "New Status Text"
Range("R1").Value = "Date"
Range("S1").Value = "New Status Date"
Range("T1").Value = "Host Status"
'Create separate worksheets
Set wb = ActiveWorkbook
Set ws = ActiveSheet
lr = ws.Range("A" & Rows.Count).End(xlUp).Row
Set rng = ws.Range("A1:A" & lr)
j = ws.[A1].CurrentRegion.Columns.Count + 1
rng.AdvancedFilter 2, , ws.Cells(1, j), True
ar = ws.Range(ws.Cells(2, j), ws.Cells(Rows.Count, j).End(xlUp))
ws.Columns(j).Clear
For i = 1 To unbound(ar)
rng.AutoFilter 1, ar(i, 1)
If Not Evaluate("=ISREF('" & ar(i, 1) & "'!A10") Then
Sheets.Add(after:=Sheets(Sheets.Count)).Name = ar(i, 1)
Else
Sheets(ar(i, 1)).Move after:=Sheets(Sheets.Count)
End If
ws.Range("A1:A" & lr).Resize(, j - 1).Copy [A1]
Next
ws.AutoFilterMode = False
Sheet("Sheet1").Name = "Modified"
'Create separate files and email
For Each ws In ActiveWorkbook.Worksheets
If ws.Name <> "original" And ws.Name <> "Modified" Then
ws.Copy
Workbooks("Fee Management Macro.xlsm").Sheets("List").Copy before:=Sheets(Sheets.Count)
Range("A2:A13").Select
ActiveWorkbook.Names.Add Name:="StatusList", RefersToR1C1:="=List!R2C1:R12C1"
ActiveWorkbook.Names("StatusList").Comment = ""
Worksheets("Lis").Visible = False
Rows("2:2").Select
ActiveWindow.FreezePanes = True
With ActiveSheet
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
With .Range("S2:S" & lastrow)
.Formula = "=Now()"
End With
With .Range("T2:T") & lastrow
.Formula = "=IFERROR(VLOOKUP(RC[-4],List!C[-19]:[C-18],2,FALSE,"""")"
End With
With .Range("P2:P" & lastrow).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=Statuslist"
.IgnoreBlank = False
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = "Select Status"
.ErrorMessage = "Please select status from the list"
.ShowInput = True
.ShowError = True
End With
With .Range("Q2:Q" & lastrow).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=0", Formula2:="460"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = "Max 460 Characters"
.InputMessage = "If black, do not complete"
.ErrorMessage = "Max 460 Characters"
.ShowInput = True
.ShowError = True
End With
With .Range("R2:R" & lastrow).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlGreater, Formula1:="11/1/2012"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = "Invalid Date"
.InputMessage = "If black, do not complete"
.ErrorMessage = "Please enter a valid date."
.ShowInput = True
.ShowError = True
End With
With .Range("P2:P" & lastrow).Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TintAndShade = 0.599993896298105
.Patterntintshade = 0
End With
With .Range("Q2:Q" & lastrow).Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.Patterntintshade = 0
End With
With .Range("R2:R" & lastrow).Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.Patterntintshade = 0
End With
With .Range("R2:R" & lastrow).FormatConditions
.Add Type:=xlExpression, Formula1:= _
"=$P2=""Contacted Insured"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TinAndShade = 0.599963377788629
End With
Selection.FormatConditions(1).StopIfTrue = False
End With
With .Range("R2:R" & lastrow).FormatConditions
.Add Type:=xlExpression, Formula1:= _
"=$P2=""Appointment Date Set"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TinAndShade = 0.599963377788629
End With
Selection.FormatConditions(1).StopIfTrue = False
End With
With .Range("R2:R" & lastrow).FormatConditions
.Add Type:=xlExpression, Formula1:= _
"=$P2=""Close Out Submitted"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TinAndShade = 0.599963377788629
End With
Selection.FormatConditions(1).StopIfTrue = False
End With
With .Range("R2:R" & lastrow).FormatConditions
.Add Type:=xlExpression, Formula1:= _
"=$P2=""Contacted Agent"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TinAndShade = 0.599963377788629
End With
Selection.FormatConditions(1).StopIfTrue = False
End With
With .Range("R2:R" & lastrow).FormatConditions
.Add Type:=xlExpression, Formula1:= _
"=$P2=""Other"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TinAndShade = 0.599963377788629
End With
Selection.FormatConditions(1).StopIfTrue = False
End With
End With
Rows("1:1").Select
With Selection
.Font.Bold = True
.Font.Underline = xlUnderlineStyleSingle
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
ActiveSheet.Columns("A:Z").AutoFit
ActiveSheet.Columns("A:Z").HorizontalAlignment = xlCenter
ActiveSheet.Columns("A:Z").VerticalAlignment = xlCenter
ActiveSheet.Range("A1").AutoFilter
With ActiveSheet.Sort
.SortFields.Add Key:=Range("K1"), Order:=xlAscending
.Header = xlYes
.Apply
End With
lcol = Cells(1, Columns.Count).End(xlToLeft).Column
lrow = Cells(Rows.Count, "A").End(xlUp).Row
Range(Cells(1, lcol + 1), Cells(Rows.Count, Columns.Count)).EntireColumn.Hidden = True
Range(Cells(lrow + 1, 1), Cells(Rows.Count, Columns.Count)).EntireRow.Hidden = True
Columns("C").Hidden = True
Columns("O").Hidden = True
Columns("S").Hidden = True
Columns("T").Hidden = True
Columns("U").Hidden = True
Range("A1").Select
Selection.AutoFilter
Range("R:R").Select
Selection.NumberFormat = "yyy-mm-dd;#"
Range("H;H,G:G,F;F,B:B").Select
Selection.NumberFormat = "m/d/yyy"
Range("D:D,A:A").Select
Range("A1").Activate
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Rows("1:1").Select
With Selection
.HorizontalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Columns("A:A").ColumnWidth = 25
Columns("D:D").ColumnWidth = 30
Columns("P:P").ColumnWidth = 30
Columns("Q:Q").ColumnWidth = 35
Columns("R:R").ColumnWidth = 10
Range("P:P,Q:Q,R:R").Locked = False
ActiveSheet.Protect Password:="ChrisBrianGreg2020", Userinterfaceonly:=True
FName = ws.Name & ".xlsx"
ActiveWorkbook.SaveAs FName
Set EmailText = Workbooks("Fee Management Macro.xlsm").Sheets("List").Range("M14")
Set OutWorksheet = Workbooks("Fee Management Macro.xlsm").Sheets("List")
Set OutApp = CreateObject("Outlook.Application")
Set Outmail = OutApp.CreateItem(OutAppOutMailItem)
Set OutMailDocument = Outmail.GetInspector.WordEditor
On Error Resume Next
With Outmail
.To = ""
.CC = ""
.BCC = ""
.Subject = "Weekly Inventory Status Update -" & " " & Date & " " & "-" & " " & ws.Name
.Body = ""
.Attachments.Add ActiveWorkbook.FullName
.Display
End With
On Error GoTo 0
'Copy Images to the email
For Each OutShape In OutWorksheet.Shapes
OutShape.Copy
OutMailDocument.Range(0, 1).Paste
Next
OutMailDocument.Range(0, 1).InsertBefore EmailText
Application.CutCopyMode = False
FName = Application.ActiveWorkbook.FullName
ActiveWorkbook.Saved = True
Application.ActiveWorkbook.ChangeFileAccess xlReadOnly
Kill FName
Application.ActiveWorkbook.Close False
End If
Next ws
Set Outmail = Nothing
Set OutApp = Nothing
Application.ScreenUpdating = True
End Subenter code here

VBA Macro Not 'Saving As'

I have a macro which applies conditional formatting and filters. The macro should filter the file and save this out, it should then remove filters and filter again using different columns and save these results to another file. The macro is running but the files don't seem to be saving?
Code
Sub Customer_Connections()
'
' Macro1 Macro
'
Application.ScreenUpdating = False
' Email Must Be In Column F
'Duplicate Email
Columns("F:F").Select
Selection.FormatConditions.AddUniqueValues
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Selection.FormatConditions(1).DupeUnique = xlDuplicate
With Selection.FormatConditions(1).Font
.Color = -16383844
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13551615
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Rows("1:1").Select
Selection.AutoFilter
ActiveSheet.Range("$A$1:$Z$999999").AutoFilter Field:=6, Criteria1:=RGB(255, _
199, 206), Operator:=xlFilterCellColor
ActiveWorkbook.SaveCopyAs ("Duplicate_Emails-" & Format(Now(), "ddmmyyyy") & ".xlsm")
'More Than One #
With Sheets("Customer Connections")
.Columns("G:G").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
.Columns("G:G").NumberFormat = "General"
Cells.Select
Selection.AutoFilter
With .Range("G2:G" & .Range("A" & .Rows.Count).End(xlUp).Row)
.Formula = "=LEN(RC[-1])-LEN(SUBSTITUTE(RC[-1],""#"",""""))"
.Copy
.PasteSpecial xlPasteValues
End With
Range("G1").Select
ActiveCell.FormulaR1C1 = "Count Of #"
Rows("1:1").Select
Selection.AutoFilter
ActiveSheet.Range("$A$1:$L$999999").AutoFilter Field:=7, Criteria1:="2"
End With
ActiveWorkbook.SaveCopyAs ("Two_#_In_Emails-" & Format(Now(), "mmddyyyy") & ".xlsm")
End Sub
Try this:
ActiveWorkbook.SaveCopyAs ActiveWorkbook.Path & _
"\Two_#_In_Emails-" & Format(Now(), "mmddyyyy") & ".xlsm"

Why doesn't my chart in excel 2013 auto update whenever i add in additional data?

I'm still new to VBA thus I don't have much knowledge in VBA. Regarding this matter I've searched it online and tried most of the given solutions on Stack Overflow and still couldn't make it work. The only way that work is by doing it manually daily which I hope not to. Everyday I will add data into the worksheet to generate a comparison chart for me. I've tried using various method :
- chart.refresh
- do events
- refreshall
Sadly, none of them work for my workbook. Other than that, I have 2 chart that needs to be updated in a worksheet and I have 3 worksheets. So I will be literally updating 6 charts at once. Is there a way to make it work without doing it manually ?
This is the code that I'm working on right now and updating the chart is the last part already.
Sub trial()
Dim wb As Workbook, wb2 As Workbook, wb3 As Workbook
Dim ws As Worksheet
Dim fn As String
Set wb = ActiveWorkbook
Set ws = Sheets.Add(After:=Sheets(Worksheets.Count))
Dim Ret
Ret = Application.GetOpenFilename("Lkl Files (*.lkl), *.lkl")
If Ret <> False Then
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=Range("$A$1"))
.Name = "SPC_PLTB_450B_12092107_25°C_CW"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 65001
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileDecimalSeparator = ","
.TextFileThousandsSeparator = "."
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End If
Sheets(2).Activate
'this is for the date (loop)
Dim FirstCell As String
Dim i As Integer
FirstCell = "C19"
Range(FirstCell).Select
Do Until ActiveCell.Value = ""
If ActiveCell.Value = "" Then
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
ActiveCell = Format(Date, "mm/dd/yyyy")
ws.Activate
ws.AutoFilterMode = False
ws.Range("$A$9:$P$417").AutoFilter Field:=5, Criteria1:= _
"1"
Range("F31:F401").Select
Selection.Copy
Sheets(2).Activate
'this is for the raw data
FirstCell = "D19"
Range(FirstCell).Select
Do Until ActiveCell.Value = ""
If ActiveCell.Value = "" Then
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Sheets(3).Activate
FirstCell = "C19"
Range(FirstCell).Select
Do Until ActiveCell.Value = ""
If ActiveCell.Value = "" Then
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
ActiveCell = Format(Date, "mm/dd/yyyy")
ws.Activate
Range("D31:D401").Select
Application.CutCopyMode = False
Selection.Copy
Sheets(3).Activate
FirstCell = "D19"
Range(FirstCell).Select
Do Until ActiveCell.Value = ""
If ActiveCell.Value = "" Then
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Sheets(4).Activate
FirstCell = "C19"
Range(FirstCell).Select
Do Until ActiveCell.Value = ""
If ActiveCell.Value = "" Then
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
ActiveCell = Format(Date, "mm/dd/yyyy")
ws.Activate
Range("G31:G401").Select
Application.CutCopyMode = False
Selection.Copy
Sheets(4).Activate
FirstCell = "D19"
Range(FirstCell).Select
Do Until ActiveCell.Value = ""
If ActiveCell.Value = "" Then
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Worksheets(5).Delete
End Sub

Extract data from Excel workbook with specific procedure to report sheet

Here is the problem in my situation:
My workbook counts from the first of the month till the 15th. (sheet 1-15)
Sometimes it happens that there are 3 weeks-counts in half a month.
The weeks are counted from Monday till Sunday in de excell cels.
NOTE: I have hidden some rows and columns due to work with dates.
Now what I should establish with VB is a monthly report that shows me on how many jobs each employeé has done due to make a calculation of workspeed/ job.
All the jobs are variable and can be selected in each day of de workbook (see listed jobs sheets(1).thisworkbook.
It is possible that I have to give weekly evaluations, so it is nessecery that VB wil still use the same wbnew and expand the input of the daily workhours.
I already made a 'partial' code to start with but I can not handle to the rest.
The code should look for how many employees there are. (this I fill in in sheet(“1”) of workbook).
It should look in each workday sheet (“1”) –sheet(“15) for:
• Does the employee exist?
• Wat day of sheet we are
• Which jobs it has done (jobdescription + code job required in listing)
• If job already exist just fill in in the same row, but in the right Colum of date, if the job is not done, don't show the jobname, don't show the jobcode
• How many time spend on the job
• To control if the counting is correct you can see the total of hours in column (AA) in sheet (“15”) of workbook and cel (“S15”) of montly reportsheet
(in this case both have 15hours displayed = ok).
I have a workbook and a example of reportsheet posted.
In the workbook you will find also my attemt to start with a code (see remarks)
Hopefully someone can help me out.
dowloadlink Workbooks klick here first
here is my attemps but it is far from what I really need to do
Sub Macro1()
'
' Macro1 Macro
'
Dim wbNew As Workbook
'I need here VBA to look for if the file "per 1-15 exists and don't create a new file but just exand the data
'I need something like for each ws of thisworkbook
'also the rest of the required formula is too difficult for me
'Does the employee exist?
'Wat day of sheet we are
'Which jobs it has done (jobdescription + code job required in listing)
'If job already exist just fill in in the same row, but in the right Colum of date, if the job is not done, don't show the jobname, don't show the jobcode
'How many time spend on the job
'To control if the counting is correct you can see the total of hours in column (AA) in sheet (“15”) of workbook and cel (“S15”) of montly reportsheet (in this case both have 15hours displayed = ok).
'you can have a look at my example reportsheet
ThisWorkbook.Sheets(1).Activate
Range("A1:S53").Select
Range("S53").Activate
Selection.Copy
Set wbNew = Workbooks.Add
wbNew.Sheets(1).Activate
Range("A1:S53").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
wbNew.Sheets(1).Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range("A1").Select
ActiveSheet.Paste
ThisWorkbook.Sheets(1).Activate
Range("C12").Select
Application.CutCopyMode = False
Selection.Copy
wbNew.Sheets(1).Activate
Range("C12").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ThisWorkbook.Sheets("1").Activate
Sheets("1").Select
Range("B8").Select
Application.CutCopyMode = False
Selection.Copy
wbNew.Sheets(1).Activate
Range("M5").Select
wbNew.Sheets(1).Paste
Range("L7:Q7").Select
Selection.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=$C$12"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Range("R7:S7").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.NumberFormat = "0"
With Selection.FormatConditions(1).Font
.Bold = True
.Italic = False
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("A1:S53").Select
Application.CutCopyMode = False
ActiveSheet.PageSetup.PrintArea = "$A$1:$S$53"
Application.PrintCommunication = False
Application.PrintCommunication = True
ActiveSheet.PageSetup.PrintArea = "$A$1:$S$53"
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 600
.CenterHorizontally = False
.CenterVertically = False
.Orientation = xlPortrait
.Draft = False
.PaperSize = xlPaperA4
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
.PrintErrors = xlPrintErrorsDisplayed
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
End With
Application.PrintCommunication = True
' I also should hide row 13 , but it gives strage vieuws at the moment
Sheets(1).Name = Range("M5").Value
Sheets.Add After:=ActiveSheet
ThisWorkbook.Sheets(1).Activate
Range("A1:S53").Select
Range("S53").Activate
Selection.Copy
wbNew.Sheets(2).Activate
Range("A1:S53").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
wbNew.Sheets(2).Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range("A1").Select
ActiveSheet.Paste
ThisWorkbook.Sheets(1).Activate
Range("C12").Select
Application.CutCopyMode = False
Selection.Copy
wbNew.Sheets(1).Activate
Range("C12").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ThisWorkbook.Sheets("1").Activate
Sheets("1").Select
Range("B9").Select
Application.CutCopyMode = False
Selection.Copy
wbNew.Sheets(2).Activate
Range("M5").Select
wbNew.Sheets(2).Paste
Range("L7:Q7").Select
Selection.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=$C$12"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Range("R7:S7").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.NumberFormat = "0"
With Selection.FormatConditions(1).Font
.Bold = True
.Italic = False
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("A1:S53").Select
Application.CutCopyMode = False
ActiveSheet.PageSetup.PrintArea = "$A$1:$S$53"
Application.PrintCommunication = False
Application.PrintCommunication = True
ActiveSheet.PageSetup.PrintArea = "$A$1:$S$53"
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 600
.CenterHorizontally = False
.CenterVertically = False
.Orientation = xlPortrait
.Draft = False
.PaperSize = xlPaperA4
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
.PrintErrors = xlPrintErrorsDisplayed
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
End With
Application.PrintCommunication = True
' I also should hide row 13 , but it gives strage vieuws at the moment
Sheets(2).Name = Range("M5").Value
' instead of writing "per 1-15" down here, I should refer to Range("R7").Value, but it is not working
' in Cel R7 there is written "per 1-15" as value now(I believe)
ActiveWorkbook.SaveAs Filename:= _
"C:\Path\" & "per 1-15" & " " & Format(Range("C12"), "mmm") & ".xlsx"
FileFormat = xlOpenXMLWorkbook
Range("A15").Select
ActiveWindow.Close
End Sub
in order to start somewhere with a constructive way you can find a second attemt below
'in order to start with a creation of a new workbook I should do some handlings first
'I want to create a workbook where the names of the employees are shown , with in the sheetnames the names of the employees
'in thisworkbook.sheet "1" there is a list of 30 names listed Column B8:B37, that I shoud copy into a new workbook
Dim i As Long
Dim StartRow As Long
Dim LastRow As Long
Dim wbnew As Workbook
Dim wsNew As Worksheet
'STARTING FROM THIS WORKBOOK
'Set Start Row thisworkbook
StartRow = 8
'Set Last Row thisworkbook
LastRow = .Range("B" & .Rows.Count).End(xlUp).Row
For i = StartRow To LastRow
'copy the name into a cel "M5" of wbnew (see below)
If .Range("B" & i).Value <> "NAME" Then
' if cel is empty do nothing
If .Range("B" & i).Value <> "" Then
On Error Resume Next
'create new workbook
Set wbnew = Workbooks.Add
' launch here the sheet routine below
'wbnew sheet routine Handling---------------------------------------------------------
'when in this specific cells there is written "Name" , that Cell should not be copied to a new sheet wbnew
'when in cels B8:B37 there is written a name ,the code should make a new workbook (wbnew) with following procedures
'this selection is always a copy from this specific sheet
ThisWorkbook.Sheets(1).Activate
Range("A1:S53").Select
Range("S53").Activate
Selection.Copy
'here I need to write activate always the new sheet wbnew
wbnew.Sheets(2).Activate
Range("A1:S53").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
'here I need to write select always the new sheetwbnew
wbnew.Sheets(2).Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range("A1").Select
ActiveSheet.Paste
' this has to stay like this
ThisWorkbook.Sheets(1).Activate
Range("C13").Select
Application.CutCopyMode = False
Selection.Copy
'here I need to write select always the new sheet wbnew
wbnew.Sheets(2).Activate
Range("C13").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ThisWorkbook.Sheets("1").Activate
' this has to stay like this
Sheets("1").Select
Range("B9").Select
Application.CutCopyMode = False
Selection.Copy
'here I need to write activate always the new sheet wbnew
wbnew.Sheets(2).Activate
Range("M5").Select
wbnew.Sheets(2).Paste
Range("L7:Q7").Select
Selection.FormatConditions.delete
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=$C$13"
Selection.FormatConditions (Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Bold = True
.Italic = False
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("A1:S53").Select
Application.CutCopyMode = False
ActiveSheet.PageSetup.PrintArea = "$A$1:$S$53"
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.PrintTitleRows = ""
.PrintTitleColumns = ""
End With
Application.PrintCommunication = True
ActiveSheet.PageSetup.PrintArea = "$A$1:$S$53"
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = ""
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
.LeftMargin = Application.InchesToPoints(0.708661417322835)
.RightMargin = Application.InchesToPoints(0.708661417322835)
.TopMargin = Application.InchesToPoints(0.748031496062992)
.BottomMargin = Application.InchesToPoints(0.748031496062992)
.HeaderMargin = Application.InchesToPoints(0.31496062992126)
.FooterMargin = Application.InchesToPoints(0.31496062992126)
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 600
.CenterHorizontally = False
.CenterVertically = False
.Orientation = xlPortrait
.Draft = False
.PaperSize = xlPaperA4
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
.PrintErrors = xlPrintErrorsDisplayed
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
.EvenPage.LeftHeader.Text = ""
.EvenPage.CenterHeader.Text = ""
.EvenPage.RightHeader.Text = ""
.EvenPage.LeftFooter.Text = ""
.EvenPage.CenterFooter.Text = ""
.EvenPage.RightFooter.Text = ""
.FirstPage.LeftHeader.Text = ""
.FirstPage.CenterHeader.Text = ""
.FirstPage.RightHeader.Text = ""
.FirstPage.LeftFooter.Text = ""
.FirstPage.CenterFooter.Text = ""
.FirstPage.RightFooter.Text = ""
End With
Range("R7:S7").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.NumberFormat = "0"
Range("A4:H9").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Rows("10:10").Select
Selection.EntireRow.Hidden = True
Application.PrintCommunication = True
'the new sheet should be named to this specific cel value (this is the name we copied form sheet(1) from thisworkbook
'now it is referring to a specific sheet of wbnew, but that is not ok, should be changed
Sheets(2).Name = Range("M5").Value
Range("A15").Select
'later I have to Call here an other Sub in order to do aditional extractions
Call sub_followlater
wbnew.Activate
'create a new sheet here
set wsNew = wbNew.Sheets.Add After:=ActiveSheet
'save the new workbook wbnew
wbnew.SaveAs Filename:= _
"C:\Path\" & "per 1-15" & " " & Format(Range("C13"), "mmmm") & " " & Format(Range("C13"), "YYYY") & ".xlsx"
FileFormat = xlOpenXMLWorkbook
ActiveWindow.Close
Hopefully someone is feeling challanged enouhg to help me out with this.
thanks in advance...
One solution is to write a macro that will copy the rows with data to another sheet, so you get all the entries for all jobs, all dates on one page. This will streamline the code because you will not be looking at blank rows for your report preparation.
Once you have the data all transferred to a single worksheet you can loop through the rows in a second macro that copies the data to separate pages based on the persons name.
This involves a good amount of skill in VBA using loops to evaluate and copy the rows from many tabs to one in the first pass, then from the one worksheet to many in the second pass. You will not be able to complete this with just the macro recorder. If you are up to the challenge but lacking in knowledge of the VBA language and the Excel object model I suggest getting one of John Walkenbach's books on Excel Power Programming with VBA.
Good luck.

Find and replace text in a separate Word document from a user input variable

I made a VBA macro that generates a MailMerge from an Excel spreadsheet creating the new document in Word.
I need to run a Find and Replace on a particular phrase ('ANTHXXXX') in the Word document with the user input variable InputtedModuleCode.
The macro runs without errors, but I can't get it to find and replace. I have included the entire macro script below. The relevant line of the script is underneath the comment:
' find and replace module code
...about 10 lines from the bottom of the script.
Sub AAMerge()
'
' AAMerge Macro
'
'
'Prompt user to input Module Code
Dim InputtedModuleCode As String
InputtedModuleCode = InputBox("Enter Module Code here, e.g. ANTH1001")
'Prompt user to input Module Code
Dim InputtedSubmissionDeadline As String
InputtedSubmissionDeadline = InputBox("Enter essay submission deadline. Must be format dd/mm/yyyy hh:mm:ss")
'Copy data into new spreadsheet
Cells.Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Application.CutCopyMode = False
With Selection.Font
.Name = "Arial"
.Size = 12
.StrikeThrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
End With
With Selection.Font
.Name = "Arial"
.Size = 10
.StrikeThrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
End With
' Move GradeMark Grade Column
Columns("H:H").Select
Selection.Copy
Columns("P:P").Select
ActiveSheet.Paste
' Delete Overlap/Internet Overlap/Publications Overlap/Student Papers Overlap columns
Columns("C:C").Select
Selection.Delete Shift:=xlToLeft
Selection.Delete Shift:=xlToLeft
Columns("F:J").Select
Selection.Delete Shift:=xlToLeft
' insert Portico SCN formula
Range("F2").Select
ActiveCell.FormulaR1C1 = "SCN (Portico)"
Range("F3").Select
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP((UPPER(CONCATENATE(RC[-5],""_"",(LEFT(RC[-4],1)),""_" & InputtedModuleCode & """))),'N:\EssaySubTrial\[Student List 201213.xls]Sheet1'!C1:C9,6,FALSE),"""")"
Range("F3").Select
Dim LR As Integer
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("F3").AutoFill Destination:=Range("F3:F" & LR), Type:=xlFillDefault
' insert Portico student email
Range("G2").Select
ActiveCell.FormulaR1C1 = "Email (Portico)"
Range("G3").Select
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP((UPPER(CONCATENATE(RC[-6],""_"",(LEFT(RC[-5],1)),""_" & InputtedModuleCode & """))),'N:\EssaySubTrial\[Student List 201213.xls]Sheet1'!C1:C9,7,FALSE),"""")"
Range("G3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("G3").AutoFill Destination:=Range("G3:G" & LR), Type:=xlFillDefault
' insert Portico student department name
Range("H2").Select
ActiveCell.FormulaR1C1 = "Dept (Portico)"
Range("H3").Select
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP((UPPER(CONCATENATE(RC[-7],""_"",(LEFT(RC[-6],1)),""_" & InputtedModuleCode & """))),'N:\EssaySubTrial\[Student List 201213.xls]Sheet1'!C1:C9,9,FALSE),"""")"
Range("H3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("H3").AutoFill Destination:=Range("H3:H" & LR), Type:=xlFillDefault
' Format column headers and widths
Rows("2:2").Select
Selection.Font.Bold = True
Columns("G:G").EntireColumn.AutoFit
Columns("H:H").EntireColumn.AutoFit
'Sort alphabetically by surname/firstname
Range("A3").Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A3:A" & LR) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("B3:B" & LR) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A2:H" & LR)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
' Move SCN column from Column G to Column C
Columns("C:C").Select
Selection.Insert Shift:=xlToRight
Columns("G:G").Select
Selection.Cut Destination:=Columns("C:C")
Columns("C:C").Select
' Remove ' at ' from Date Uploaded column
Columns("F").Replace What:=" at ", Replacement:=" ", LookAt:=xlPart
' Format date and add extra date columns
Columns("F:F").Select
Selection.NumberFormat = "dd/mm/yyyy hh:mm:ss"
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("G2").Select
ActiveCell.FormulaR1C1 = "Extension Date"
Range("F2").Select
ActiveCell.FormulaR1C1 = "Essay Deadline"
Columns("F:G").Select
Selection.NumberFormat = "dd/mm/yyyy hh:mm:ss"
' Add user inputted submission date
Range("F3").Select
ActiveCell.FormulaR1C1 = CDate(InputtedSubmissionDeadline)
Range("F3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("F3").AutoFill Destination:=Range("F3:F" & LR), Type:=xlFillCopy
' Cleanup column width and add extra column
Columns("F:F").EntireColumn.AutoFit
Range("I2").Select
ActiveCell.FormulaR1C1 = "Days late"
Columns("J:J").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("J2").Select
ActiveCell.FormulaR1C1 = "Penalty (%pts)"
' Number of days late column
Range("I3").Select
ActiveCell.FormulaR1C1 = _
"=IF((RC[-1]-(IF(RC[-2]=0,RC[-3],RC[-2]))<=0), 0, (ROUNDUP(RC[-1]-(IF(RC[-2]=0,RC[-3],RC[-2])),0)))"
Range("I3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("I3").AutoFill Destination:=Range("I3:I" & LR), Type:=xlFillDefault
' Penalty %pts column
Range("J3").Select
ActiveCell.FormulaR1C1 = _
"=(IF(RC[-1]>7,100,(IF(RC[-1]>1,10,IF(RC[-1]>0,5,0)))))"
Range("J3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("J3").AutoFill Destination:=Range("J3:J" & LR), Type:=xlFillDefault
' Add marks columns
Range("M2").Select
ActiveCell.FormulaR1C1 = "1stM Grade"
Range("N2").Select
ActiveCell.FormulaR1C1 = "2ndM Grade"
Range("O2").Select
ActiveCell.FormulaR1C1 = "Final Grade"
Range("O2").Select
ActiveCell.FormulaR1C1 = "Agreed Grade"
' Add final grade colum
Range("P2").Select
ActiveCell.FormulaR1C1 = "Final Grade (after penalty)"
Range("P3").Select
ActiveCell.FormulaR1C1 = "=MAX(0,(RC[-1]-RC[-6]))"
Range("P3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("P3").AutoFill Destination:=Range("P3:P" & LR), Type:=xlFillDefault
' Add column with formatted submission deadline date that can be read by MailMerge in word
Range("Q2").Select
ActiveCell.FormulaR1C1 = "Submission Deadline (formatted)"
Range("Q3").Select
ActiveCell.FormulaR1C1 = "=TEXT(RC[-11],""dd-mmm-YYYY HH:mm:ss"")"
Range("Q3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("Q3").AutoFill Destination:=Range("Q3:Q" & LR), Type:=xlFillDefault
' Add column with formatted submission deadline date that can be read by MailMerge in word
Range("R2").Select
ActiveCell.FormulaR1C1 = "Date Uploaded (formatted)"
Range("R3").Select
ActiveCell.FormulaR1C1 = "=TEXT(RC[-10], ""dd-mmm-YYYY HH:mm:ss"")"
Range("R3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("R3").AutoFill Destination:=Range("R3:R" & LR), Type:=xlFillDefault
'Save file
ActiveWorkbook.SaveAs Filename:="N:\EssaySubTrial\" & InputtedModuleCode & " Datasheet " & _
Format(Now(), "yyyy-mm-dd HHmmss") & ".xlsx", FileFormat:=xlOpenXMLWorkbook, Password:="", _
WriteResPassword:="", ReadOnlyRecommended:=False, CreateBackup:=False
Sheets("Sheet3").Select
ActiveWindow.SelectedSheets.Delete
Sheets("Sheet2").Select
ActiveWindow.SelectedSheets.Delete
' do Mailmerge
Dim wdOutputName, wdInputName As String
wdOutputName = ThisWorkbook.Path & "\Coversheet " & Format(Date, "d mmm yyyy")
wdInputName = ThisWorkbook.Path & "\coursework-coversheet-template-merged-updated.docx"
' open the mail merge layout file
Dim wdDoc As Object
Set wdDoc = GetObject(wdInputName, "Word.document")
wdDoc.Application.Visible = True
With wdDoc.MailMerge
.MainDocumentType = wdFormLetters
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
.Execute Pause:=False
End With
' find and replace module code
wdDoc.Application.ActiveDocument.Content.Find.Execute "ANTHXXXX", ReplaceWith:=InputtedModuleCode, Replace:=wdReplaceAll
' show and save output file
wdDoc.Application.Visible = True
wdDoc.Application.ActiveDocument.SaveAs wdOutputName
' cleanup
wdDoc.Close SaveChanges:=False
Set wdDoc = Nothing
End Sub
I haven't check the remainder of the code but if your problem is merely the Find and replace at the bottom of the code then the following should do the job (setting the replacement from a string shouldn't matter):
'I'd recommend leaving all these options in
With wdDoc.Application.Selection.Find
.ClearFormatting
.Text = "ANTHXXXX"
.Replacement.Text = InputtedModuleCode
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchKashida = False
.MatchDiacritics = False
.MatchAlefHamza = False
.MatchControl = False
.MatchByte = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchFuzzy = False
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
One other thing if you're interested, the code wdDoc.Application.ActiveDocument.SaveAs does exactly the same thing as wdDoc.SaveAs.

Resources