Here is my code below that opens up yesterdays file Tuesday-Friday and the last 3 days on a Monday.
There is now a need to make a weekly version of this and i feel the code may get too long.
Is there a better way to do this then recreating the loop 7 times?
I am thinking i could do another loop that says that while column G (which only has information if updated in ) is empty then take the date in the respective cell in column A and keep opening files from the date in column A to yesterdays date? (pic for reference on what i mean) so it would fill every day from 13/09/2021 to 19/09/2021.
Also it would be nice if anyone had any pointers about making this code more robust and/or efficient as I am quite new to VBA.
Sub OpenManagersFileAndSelectColumns()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer, directory3day As String, fileName3day As String, directory2day As String, fileName2day As String, DateStringFS As String, AlteryxFP As String
' Turn off screen updating and displaying alerts.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Creating Dynamic Elements for directories and file names.
' Create the year, day amd month year
'For - 1 Days (used in two places)
YearString = Format((Date - 1), "yyyy")
MonthYearString = Format((Date - 1), "mmm yyyy")
DateString = Format((Date - 1), "dd-mm-yyyy")
'For - 2 Days
YearString2day = Format((Date - 2), "yyyy")
MonthYearString2day = Format((Date - 2), "mmm yyyy")
DateString2day = Format((Date - 2), "dd-mm-yyyy")
'For - 3 Days
YearString3day = Format((Date - 3), "yyyy")
MonthYearString3day = Format((Date - 3), "mmm yyyy")
Dim DateString3day As String
'Date for File Name
DateStringFS = Format((Date), "dd.mm.yy")
'Gets username of the device for comp and whether or not
comp = Environ("username")
'Gets Alteryx Output
If Environ("username") = "SP" Then
AlteryxFP = "Alteryx Output\"
Else
AlteryxFP = ""
End If
' Initialize the variable directory. We use the Dir function to find the first *.csv ?? file stored in this directory. ( this can be changed to xls if necessary
'For Today - 1 day (used in two places)
directory = "C:\Users\" & comp & "\Dropbox (SHG)\" & AlteryxFP & "\Daily Finance & Revenue Data\1. Daily Occupancy Output\Site 5\" & YearString & "\" & MonthYearString & "\" & DateString & "\"
'For Today - 2 Days
directory2day = "C:\Users\" & comp & "\Dropbox (SHG)\" & AlteryxFP & "\Daily Finance & Revenue Data\1. Daily Occupancy Output\Site 5\" & YearString2day & "\" & MonthYearString2day & "\" & DateString2day & "\"
'For Today - 3 Days
directory3day = "C:\Users\" & comp & "\Dropbox (SHG)\" & AlteryxFP & "\Daily Finance & Revenue Data\1. Daily Occupancy Output\Site 5\" & MonthYearString3day & "\" & DateString3day & "\"
'Ensures the current file is activated and clears previous content.
Windows("YORYK Daily Report " & DateStringFS & "$.xlsb").Activate
Sheets("Actual data").Activate
Rows("4:7").Select
Selection.ClearContents
'If its a monday then it will open the last 3 days, it is the rest of the week it will open the previous day.
If Format(Date, "w") = 2 Then
' Today - 1 days
fileName = Dir(directory & "*manager*.csv")
' The variable fileName now holds the name of the first Excel file found in the directory. Add a Do While Loop.
Do While fileName <> ""
' There is no simple way to copy worksheets from closed Excel files. Therefore we open the Excel file.
Workbooks.Open (directory & fileName), local:=True
' Import the sheets from the Excel file into import-sheet.xls.
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("YORYK Daily Report " & DateStringFS & "$.xlsb").Worksheets.Count
Windows(fileName).Activate
' If the date in the file is TODAY -1 then accept, otherwise error message.
If Range("AG2") = (Date - 1) Then
Rows("2:2").Select
Selection.Copy
Windows("YORYK Daily Report " & DateStringFS & "$.xlsb").Activate
Sheets("Actual data").Activate
Rows("7:7").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Range("A4:AG5").Select
Application.CutCopyMode = False
Else
MsgBox "Date in file does not match " & DateString
' End If for checking the date for day - 1
End If
Next sheet
'Close the Excel file.
Workbooks(fileName).Close
'The Dir function is a special function. To get the other Excel files, you can use the Dir function again with no arguments.
fileName = Dir()
'Note: When no more file names match, the Dir function returns a zero-length string ("").
'As a result, Excel VBA will leave the Do While loop.
'End of loop for day - 1 file open and paste.
Loop
' Today - 2 days.
fileName2day = Dir(directory2day & "*manager*.csv")
' The variable fileName now holds the name of the first Excel file found in the directory. Add a Do While Loop.
Do While fileName2day <> ""
' There is no simple way to copy worksheets from closed Excel files. Therefore we open the Excel file.
Workbooks.Open (directory2day & fileName2day), local:=True
' Import the sheets from the Excel file into this sheet.
For Each sheet In Workbooks(fileName2day).Worksheets
total = Workbooks("YORYK Daily Report " & DateStringFS & "$.xlsb").Worksheets.Count
Windows(fileName2day).Activate
If Range("AG2") = Date - 2 Then
Rows("2:2").Select
Selection.Copy
Sheets("Actual data").Activate
Rows("6:6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Else
MsgBox "Date in file does not match " & DateString2day
End If
Next sheet
'Close the Excel file.
Workbooks(fileName2day).Close
'The Dir function is a special function. To get the other Excel files, you can use the Dir function again with no arguments.
fileName2day = Dir()
'Note: When no more file names match, the Dir function returns a zero-length string ("").
'As a result, Excel VBA will leave the Do While loop.
Loop
' Today - 3 days
fileName3day = Dir(directory3day & "*manager*.csv")
' The variable fileName now holds the name of the first Excel file found in the directory. Add a Do While Loop.
Do While fileName3day <> ""
' There is no simple way to copy worksheets from closed Excel files. Therefore we open the Excel file.
Workbooks.Open (directory3day & fileName3day), local:=True
' Import the sheets from the Excel file into import-sheet.xls.
For Each sheet In Workbooks(fileName3day).Worksheets
total = Workbooks("YORYK Daily Report " & DateStringFS & "$.xlsb").Worksheets.Count
Windows(fileName3day).Activate
'If Date in file is TODAY - 3 then accept and paste info otherwise error message.
If Range("AG2") = Date - 3 Then
Rows("1:2").Select
Selection.Copy
Windows("YORYK Daily Report " & DateStringFS & "$.xlsb").Activate
Sheets("Actual data").Activate
Rows("4:5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Else
MsgBox "Date in file does not match " & DateString3day
' End If for day - 3
End If
Next sheet
'Close the Excel file.
Workbooks(fileName3day).Close
'The Dir function is a special function. To get the other Excel files, you can use the Dir function again with no arguments.
fileName3day = Dir()
'Note: When no more file names match, the Dir function returns a zero-length string ("").
'As a result, Excel VBA will leave the Do While loop.
'End Loop for Today - 3
Loop
' End of loop, now cleaning data, for 3 days section
' Next step is to select the right columns of data and run calculations to get TR, RR, OCC, OOO, ADR for the 3 day period.
Range("A4:AF7").Select
Selection.delete Shift:=xlToLeft
Range("K4:AD7").Select
Selection.delete Shift:=xlToLeft
Range("AE4:DO7").Select
Selection.delete Shift:=xlToLeft
Range("AF4:AT7").Select
Selection.delete Shift:=xlToLeft
Range("AH4:CE7").Select
Selection.delete Shift:=xlToLeft
Columns("AE:AG").Select
Selection.Cut
Columns("C:C").Select
Selection.INSERT Shift:=xlToRight
Columns("F:M").Select
Selection.INSERT Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Windows("YORYK Daily Report " & DateStringFS & "$.xlsb").Activate
Sheets("Actual data").Activate
Columns("A:A").Select
Selection.NumberFormat = "m/d/yyyy"
Range("G4").Select
ActiveCell.FormulaR1C1 = "Rms"
Range("H4").Select
ActiveCell.FormulaR1C1 = "G Rms"
Range("I4").Select
ActiveCell.FormulaR1C1 = "Rm Rev"
Range("J4").Select
ActiveCell.FormulaR1C1 = "ADR"
Range("K4").Select
ActiveCell.FormulaR1C1 = "OOO Rms"
Range("L4").Select
ActiveCell.FormulaR1C1 = "Total Rev"
Range("G5").Select
ActiveCell.FormulaR1C1 = "=RC[-4]+RC[-3]"
Range("I5").Select
ActiveCell.FormulaR1C1 = "=RC[-7]-RC[13]"
Range("J5").Select
ActiveCell.FormulaR1C1 = "=RC[-1]/RC[-3]"
Range("K5").Select
ActiveCell.FormulaR1C1 = "=RC[-6]"
Range("L5").Select
ActiveCell.FormulaR1C1 = "=SUM(RC[-10],RC[2]:RC[9])-SUM(RC[10]:RC[29])"
Range("G5:L5").Select
Selection.AutoFill Destination:=Range("G5:L7"), Type:=xlFillDefault
Range("G5:L7").Select
Range("G4").Select
' Colouring the titles to get notify it is done.
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.FormulaR1C1 = "Rms"
Range("H4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.FormulaR1C1 = "G Rms"
Range("I4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.FormulaR1C1 = "Rm Rev"
Range("J4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.FormulaR1C1 = "ADR"
Range("K4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.FormulaR1C1 = "OOO Rms"
Range("L4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.FormulaR1C1 = "Total Rev"
Range("G4:L4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = 0
.PatternTintAndShade = 0
End With
' This else is for days where day does not = monday, so any other day of the week.
Else
fileName = Dir(directory & "*manager*.csv")
' The variable fileName now holds the name of the first Excel file found in the directory. Add a Do While Loop.
Do While fileName <> ""
' There is no simple way to copy worksheets from closed Excel files. Therefore we open the Excel file.
Workbooks.Open (directory & fileName), local:=True
' Import the sheets from the forecast file into this sheet
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("YORYK Daily Report " & DateStringFS & "$.xlsb").Worksheets.Count
Windows(fileName).Activate
If Range("AG2") = Date - 1 Then
Rows("1:2").Select
Selection.Copy
Windows("YORYK Daily Report " & DateStringFS & "$.xlsb").Activate
Sheets("Actual data").Activate
Rows("4:5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Else
MsgBox "Date in file does not match " & DateString
End If
Next sheet
'Close the Excel file.
Workbooks(fileName).Close
'The Dir function is a special function. To get the other Excel files, you can use the Dir function again with no arguments.
fileName = Dir()
'Note: When no more file names match, the Dir function returns a zero-length string ("").
'As a result, Excel VBA will leave the Do While loop.
Loop
' End of loop, for 1 day set up, now cleaning data
' Next step is to select the right columns of data and run calculations to get TR, RR, OCC, OOO, ADR for one day
Range("A4:AF7").Select
Selection.delete Shift:=xlToLeft
Range("K4:AD7").Select
Selection.delete Shift:=xlToLeft
Range("AE4:DO7").Select
Selection.delete Shift:=xlToLeft
Range("AF4:AT7").Select
Selection.delete Shift:=xlToLeft
Range("AH4:CE7").Select
Selection.delete Shift:=xlToLeft
Columns("AE:AG").Select
Selection.Cut
Columns("C:C").Select
Selection.INSERT Shift:=xlToRight
Columns("F:M").Select
Selection.INSERT Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Windows("YORYK Daily Report " & DateStringFS & "$.xlsb").Activate
Sheets("Actual data").Activate
Columns("A:A").Select
Selection.NumberFormat = "m/d/yyyy"
Range("G4").Select
ActiveCell.FormulaR1C1 = "Rms"
Range("H4").Select
ActiveCell.FormulaR1C1 = "G Rms"
Range("I4").Select
ActiveCell.FormulaR1C1 = "Rm Rev"
Range("J4").Select
ActiveCell.FormulaR1C1 = "ADR"
Range("K4").Select
ActiveCell.FormulaR1C1 = "OOO Rms"
Range("L4").Select
ActiveCell.FormulaR1C1 = "Total Rev"
Range("G5").Select
ActiveCell.FormulaR1C1 = "=RC[-4]+RC[-3]"
Range("I5").Select
ActiveCell.FormulaR1C1 = "=RC[-7]-RC[13]"
Range("J5").Select
ActiveCell.FormulaR1C1 = "=RC[-1]/RC[-3]"
Range("K5").Select
ActiveCell.FormulaR1C1 = "=RC[-6]"
Range("L5").Select
ActiveCell.FormulaR1C1 = "=SUM(RC[-10],RC[2]:RC[9])-SUM(RC[10]:RC[29])"
'Colour titles for each title to mark that its done, for one day.
Range("G4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.FormulaR1C1 = "Rms"
Range("H4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.FormulaR1C1 = "G Rms"
Range("I4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.FormulaR1C1 = "Rm Rev"
Range("J4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.FormulaR1C1 = "ADR"
Range("K4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.FormulaR1C1 = "OOO Rms"
Range("L4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.FormulaR1C1 = "Total Rev"
Range("G4:L4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = 0
.PatternTintAndShade = 0
End With
' End If for -1 day vs - 3 day.
End If
'Turn on screen updating and displaying alerts again (outside the loop).
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
The answer to your question is Yes, you should probably change your code to to work down the list of dates so that it is being driven by the data. In addition, your code could benefit a lot from better use of vba which you can learn:
As noted in comments, use variables in your vba code to give access workbooks, worksheets and cell ranges instead of using Activate and Select - which should be used only if you need to change what the user sees and, even then, only right at the end of your processing, just before giving control back to the user. Your code will be easier to read and run much faster.
Use named formatting styles instead of hard-coding styles. This is much more meaningful and is much easier to change and extend if you want to improve the appearance of your workbook without having to change the vba code.
Divide the code up into functions that do a specific parts of the logic, and call the functions instead of repeating the code. If you use variables to refer to workbooks, worksheets etc, then you can pass variables to the functions. For example, the code that processes one csv file could be written as a function that is called from higher-level logic.
I think you will find that your code becomes a lot simpler and easier to read and understand.
Please, try the next code. It is not tested, of course, but its logic should be correctly applied. It opens each csv file and copy its second row to the report starting from the 7th row, backwards to the first row:
Sub tes7DaysBackArray()
Dim arr7D, arrM, arrY, d As Date, DateStringFS As String, wsAD As Worksheet, wbLoc As Workbook, AlteryxFP As String
Dim pathRoot As String, fileName As String, comp As String, ws As Worksheet, i As Long, iRow As Long
DateStringFS = Format((Date), "dd.mm.yy"): d = Date: iRow = 7
'build arrays containing the necessary formatted strinns:
arr7D = Application.Transpose(Evaluate("TEXT(DATE(" & Year(d - 7) & "," & month(d - 7) & ",row(" & Day(d - 7) & ":" & Day(d - 1) & ")),""dd-mm-yyyy"")"))
arrM = Application.Transpose(Evaluate("TEXT(DATE(" & Year(d - 7) & "," & month(d - 7) & ",row(" & Day(d - 7) & ":" & Day(d - 1) & ")),""mmm yyy"")"))
arrY = Application.Transpose(Evaluate("TEXT(DATE(" & Year(d - 7) & "," & month(d - 7) & ",row(" & Day(d - 7) & ":" & Day(d - 1) & ")),""yyyy"")"))
Debug.Print Join(arr7D, "|"): Debug.Print Join(arrM, "|"): Debug.Print Join(arrY, "|") 'just to visually see the above built arrays...
If Environ("username") = "SP" Then
AlteryxFP = "Alteryx Output\"
Else
AlteryxFP = ""
End If
pathRoot = "C:\Users\" & comp & "\Dropbox (SHG)\" & AlteryxFP & "\Daily Finance & Revenue Data\1. Daily Occupancy Output\Site 5\"
Set wsAD = Workbooks("YORYK Daily Report " & DateStringFS & "$.xlsb").Sheets("Actual data")
For i = 0 To UBound(arr7D)
fileName = pathRoot & arrY(i) & "\" & arrM(i) & "\" & arr7D(i) & "\"
fileName = dir(fileName & "*manager*.csv")
If fileName <> "" Then
Set wbLoc = Workbooks.Open(Directory & fileName, local:=True)
Set ws = wbLoc.Sheets(1) 'the single existing sheet
If CStr(Format(ws.Range("AG2").Value, "dd-mm-yyyy")) = arr7D(i) Then
wsAD.rows(iRow & ":" & iRow).Value = ws.rows("2:2").Value: iRow = iRow + 1
wbLoc.Close False
Else
MsgBox "Date in file does not match " & arr7D(i)
End If
Else
MsgBox "No any required csv file could be found in & """ & fileName & """."
End If
Next i
End Sub
I am very new to the world of Excel VBA World, I am currently working on merging multiple worksheets from different .csv files (same folder) into one giant .csv file.
Previously, I have already ran a code (successfully) to select all the data I wanted to all the .csv files in that folder. But I can't seem to merge all the sheets from these files into one....
This is the successful code
Option Explicit
Sub LoopThroughFiles()
Dim xFd As FileDialog
Dim xFdItem As Variant
Dim xFileName As String
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
If xFd.Show = -1 Then
xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
xFileName = Dir(xFdItem & "*.csv*")
Do While xFileName <> ""
With Workbooks.Open(xFdItem & xFileName)
'your code here
OP10SelectCut
End With
xFileName = Dir
Loop
End If
End Sub
Sub OP10SelectCut()
'
' OP10SelectCut 巨集
'
'
Dim TotalRow As Integer
TotalRow = Range("B1").End(xlDown).Row
Columns("B:B").Select
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlNotBetween, _
Formula1:="=-0.02", Formula2:="=0.02"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
End With
Selection.FormatConditions(1).StopIfTrue = False
Selection.AutoFilter
ActiveSheet.Range("$B$1:$B$" & TotalRow).AutoFilter Field:=1, Criteria1:=RGB(255 _
, 255, 0), Operator:=xlFilterCellColor
Columns("B:C").Select
Selection.Copy
Sheets.Add After:=ActiveSheet
Range("A1").Select
ActiveSheet.Paste
End Sub
This is the not working code
'合併多個Excel檔案
Sub GetSheets()
Path = "C:\Users\andrew-wu\Desktop\OP10TestBatch"
Filename = Dir(Path & "*.csv*")
Do While Filename <> "*.csv*"
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
'只複製第一個Sheet
If ActiveWorkbook.Sheets.Count > 0 Then
ActiveWorkbook.Sheets(1).Copy _
After:=ThisWorkbook.Sheets(1)
'每個Sheet都複製
'For Each Sheet In ActiveWorkbook.Sheets
'Sheet.Copy After:=ThisWorkbook.Sheets(1)
'Next Sheet
End If
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
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.
I have a excel sheet with a sale offer for multiple receivers each day.
The file has two tabs, Now I created a macro, to send the emails automatic.
The macro has a sub for each day.
Now one of the tabs is copied to a new worksheet than it changes one cell which has the name of the receiver in it.
After that, it sends the mail through outlook.
The sub begins with:
' Copy tab to a new worksheet
Sheets("Offer").Select
Sheets("Offer").Copy
Cells.Select
' Copy worksheet with only results to replace formulas
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
' Change the color for cell A15:C15
Range("A15:C15").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 14336204
.TintAndShade = 0
.PatternTintAndShade = 0
End With
'Format the numbers to 2 numbers after the comma
Range("D20:D47").Select
Selection.NumberFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(#_)"
' Turn alerts off
Application.DisplayAlerts = False
' Set the author
ActiveWorkbook.BuiltinDocumentProperties("Author") = "Author name"
Then for each receiver, I have a block like this:
' email1
Range("D15:H15").Select
ActiveCell.FormulaR1C1 = "name1"
ActiveWorkbook.SaveAs Filename:= _
"C:\Aanbod\Vrijdag\Filename_receivername1", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
'send mail
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = "receiver1#domain.com"
.CC = ""
.BCC = ""
.Subject = "subject here"
.Body = ""
.Attachments.Add ActiveWorkbook.FullName
.Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
And to end the sub:
' Turn alerts back on
Application.DisplayAlerts = True
' Close active window
ActiveWindow.Close
' Go to tab1
Sheets("tab1").Select
Now, this is working, but not really efficient. Also for some reason, it's not working entirely on one of the computers we use it on.
On that computer, it skips some of the receivers, so it doesn't send all emails.
Now I like to create an 3rd tab in the sales offer worksheet, with the email addresses in it, including the names of the receivers.
How can I do this?
So I rebuild the code now, so it uses a loop for generating the files and sending the mails.
This is what I got now:
Sub Maakbestanden_maandag()
Dim Sh As Worksheet
Set Sh = ThisWorkbook.Sheets("Kopers-Maandag")
Dim Ab As Worksheet
Set Ab = ThisWorkbook.Sheets("Aanbod")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Sheets("Aanbod").Select
Sheets("Aanbod").Copy
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A15:C15").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 14336204
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Range("D20:D49").Select
Selection.NumberFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(#_)"
Range("C20:C49").Select
Selection.NumberFormat = "#"
Range("E20:F49").Select
Selection.NumberFormat = "0"
Columns("E:E").ColumnWidth = 8
Columns("F:F").ColumnWidth = 6
ActiveWorkbook.BuiltinDocumentProperties("Author") = "AUTHOR NAME"
Range("G50").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-30]C:R[-1]C)"
Range("G51").Select
ActiveCell.FormulaR1C1 = "=R[-1]C/12"
Dim i As Integer
Dim last_row As Long
last_row = Application.WorksheetFunction.CountA(Sh.Range("A:A"))
For i = 2 To last_row
Range("D15:H15").Select
ActiveCell.FormulaR1C1 = Sh.Range("B" & i).Value
Range("D15:H15").Select
Application.ActiveWorkbook.SaveAs Filename:=Sh.Range("C" & i).Value, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Next i
Application.DisplayAlerts = True
ActiveWindow.Close
MsgBox "Bestanden aangemaakt"
Call Verstuuremail_maandag
End Sub
and than to send the actual mails:
Sub Verstuuremail_maandag()
Dim Sh As Worksheet
Set Sh = ThisWorkbook.Sheets("Kopers-Maandag")
Dim OA As Object
Dim msg As Object
Set OA = CreateObject("Outlook.Application")
Dim i As Integer
Dim last_row As Long
last_row = Application.WorksheetFunction.CountA(Sh.Range("A:A"))
For i = 2 To last_row
Set msg = OA.createitem(0)
msg.To = Sh.Range("A" & i).Value
msg.Subject = "Sales offer"
msg.body = ""
If Sh.Range("C" & i).Value <> "" Then
msg.attachments.Add Sh.Range("C" & i).Value
End If
DoEvents
msg.send
Next i
MsgBox "E-mails voor maandag verstuurd"
Sheets("Veilprijzen").Select
End Sub
Now when I'm testing it, it works well, but still sometimes it stops at 2/3 of the way while sending the mails (generating the files works fully everytime).
When it stops, it's trowing the following error:
vba error 5 invalid procedure call or argument
VBA marks it at: msg.send
It's odd, sometimes we get a full run on the same day, with the very same code and customer information, and sometimes it doesn't go all the way.
Any recommendation to solve this?
Im using a excel macro which generates a csv file with all my data to upload to gmail as contacts. When the file is uploaded to gmail contacts, the mobile number and the work number come correctly but the persons name comes in the notes box as "First Name: Yash".
Im attaching a sample csv file which is generated by the macro.
Download Sample CSV HERE
im using the following macro to generate the csv's:
Sub getcsv()
Application.ScreenUpdating = False
csvnewsheet
Dim myRange As Range
Dim NumRows As Integer
Set myRange = ActiveSheet.Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange)
Range("E1").Select
ActiveCell.FormulaR1C1 = "First Name"
Range("E2").Select
ActiveCell.FormulaR1C1 = "=CONCATENATE(Reports!R[5]C2,"" "",Reports!R[5]C1)"
Range("E2").Select
Selection.AutoFill Destination:=Range("E2:E" & NumRows + 1)
Range("E2:E3").Select
Columns("E:E").EntireColumn.AutoFit
hide_format
Exporttocsv
DelSht
Application.ScreenUpdating = True
End Sub
Sub hide_format()
'
' hides name & place columns and then removed the formatting
'
'
Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Selection.Delete Shift:=xlToLeft
Columns("C:C").Select
Selection.Cut
Columns("A:A").Select
Selection.Insert Shift:=xlToRight
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
Selection.Borders(xlEdgeTop).LineStyle = xlNone
Selection.Borders(xlEdgeBottom).LineStyle = xlNone
Selection.Borders(xlEdgeRight).LineStyle = xlNone
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End Sub
Sub csvnewsheet()
Dim myRange As Range
Dim NumRows As Integer
Set myRange = Worksheets("Reports").Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange) + 3
Sheets.Add.Name = Worksheets("Reports").Range("A2").Value & "_CSV"
Worksheets("Reports").Range("A6:D" & NumRows).Copy Destination:=Worksheets(Worksheets("Reports").Range("A2").Value & "_CSV").Range("A1")
Worksheets(Worksheets("Reports").Range("A2").Value & "_CSV").Columns("A:D").AutoFit
End Sub
Sub Exporttocsv()
Dim MyPath As String
Dim MyFileName As String
MyFileName = Worksheets("Reports").Range("A2").Value & "_CSV"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Worksheets(Worksheets("Reports").Range("A2").Value & "_CSV").Copy
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a Folder to Save the CSV"
.AllowMultiSelect = False
.InitialFileName = "" '<~~ The start folder path for the file picker.
If .Show <> -1 Then GoTo NextCode
MyPath = .SelectedItems(1) & "\"
End With
NextCode:
With ActiveWorkbook
.saveas Filename:=MyPath & MyFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close False
End With
End Sub
Sub DelSht()
Application.DisplayAlerts = False
Sheets(Worksheets("Reports").Range("A2").Value & "_CSV").Delete
Application.DisplayAlerts = True
End Sub
This macro generates a new sheet with the data then will do the required changes and save as CSV and then delete that sheet.
i dont know where im going wrong...but the contact names just dont come in gmail... ive tried various other methods but it still didnt work...
Please help!
This is how Gmail suggests the format of the csv file.
-
this is how you have yours formatted.
You may have to have it formatted the way Gmail suggests.