so I need a macro code for naming a worksheet with the next date on it, as in if the previous sheet is called Tue 27 then the next sheet (new one) should be Wed 28,
my current code only names it as TODAYS date, this is what I am using
Dim szTodayDate As String
szTodayDate = Format(Date, "ddd") & Format(Date, " dd")
On Error GoTo MakeSheet
Sheets(szTodayDate).Activate
Exit Sub
MakeSheet:
Dim Srt As Worksheet
Set Srt = ActiveSheet
Sheets.Add
ActiveSheet.Name = szTodayDate
Is it even possible to do this, and if so, can anyone please tell me how,
Thank you
additional note: so the macro creates a new sheet everytime I run it, and then names it with todays date, I need it instead to name it with the NEXT date, in relation to the previous sheet. so if the last sheet made (prior to macro run) is called "Sun 02" the macro should create a sheet and name it "Mon 03", assume for now that the month doesn't matter, I will not run this macro after the month ends, so on workbook Feb, "Wed 28" would be the last time I run this macro.
Reason Explained: so I need to create a new worksheet everyday for work, but I sometimes end up having to make the worksheet a day later, so lets say on sun 02 I make the sheet on time, so now I have worksheet sun 02, but then I miss it on monday, then on tuesday I make the sheet, it ends up making Sheet Tue 04, so now I'm missing Mon 03.
Possible Alternate: If I could somehow set an IF function that can check to see if worksheet with yesterdays name exists (maybe going back upto 2 days) and if not create it, that would work to. but not sure how to code said IF function either (It would also need to create it and name it as today, if today is 01).
Thank you again
An important note for the following code: in its default state it requires that the Sheet Names include the Month, so the format is "ddd dd mmm" ("Wed 28 Feb") not "ddd dd" ("Wed 28"). If, for example, the Month is stored in the FileName instead then you will need to modify the code.
We need a variable to store the most recent date found, and a Worksheet object to use in a For Each loop. We will check each Worksheet's Name and check if it IsDate. If it is, then we will see if it is later than our currently stored Date. This will fail at year end, unless you start including the Year in the Sheet Name (or File Name) too. (Since 1 Jan comes before 31 Dec)
Dim dMaxDate AS Date, wsForLoop AS Worksheet, sTestString AS String
dMaxDate = DateSerial(1900,1,0) 'Default to 0
For Each wsForLoop In ThisWorkbook.Worksheets 'Loop through every worksheet
sTestString = wsForLoop.Name 'Get the name of the sheet
If InStr(sTestString, " ") > 0 Then sTestString = Mid(sTestString, 1+InStr(sTestString, " ")) 'Remove the Weekday
'If you need to add the Month/Year from your filename, do that here
If IsDate(sTestString) Then 'Only check Worksheets with Dates for Names
If cDate(sTestString) > dMaxDate Then dMaxDate = cDate(sTestString) 'If this is a later date then store it
End If
Next wsForLoop 'Return to start of loop
If dMaxDate < DateSerial(1900, 1, 1) Then dMaxDate = Now-1 'If we have no Worksheets with Dates for Names then default to yesterday
With ThisWorkbook.Worksheets.Add 'Add a new sheet
'Change the Format if you are adding the Month and/or Year from Filename
.Name = Format(dMaxDate+1, "ddd d mmm") 'And Name it the day after our stored date
End With
try using below, you can use counter instead of 1.
SZTodayDate = Format(Date + 1, "ddd") & Format(Date + 1, " dd")
Related
I am trying to create a variable range that will update and bring in a different range of values based on what month it is.
January C8:D8
February C9:D9
March C10:D10
April C11:D11
May C12:D12
June C13:D13
July C14:D14
August C15:D15
September C16:D16
October C17:D17
November C18:D18
December C19:D19
These are the ranges I need based on what month it is.
My Existing Code:
Sub PullDataFromClosedWorkbook()
Dim Source As Workbook
Set Source = Workbooks.Open("H:\Integration Projects\Chk Req & Customer
Payment Sheet\Chk Reqs\Check Request.xlsm", True, True)
'bring to this workbook
ThisWorkbook.Activate
Worksheets("Sheet1").Range("B2:C2").Formula = Source.Worksheets("Consolidated
Summary").Range("C11:D11").Copy
Worksheets("Sheet1").Range("B2:C2").PasteSpecial xlPasteValues
Source.Close SaveChanges:=False
End Sub
My first idea was to create an if function that based on a drop down list with the months in it, that it could vlookup the month and set the range to that. Not sure how to do this in vba.
One way to do this would be to use the Month Function to return the current month number, which you can then use as an Offset from a starting range.
For example, since it's August, Month(Date) returns 8. If your starting range is C7:D7, Range("C7:D7").Offset(Month(Date)) refers to C15:D15.
So your code might look something like this (UNTESTED).
Sub PullDataFromClosedWorkbook()
Dim Source As Workbook
Set Source = Workbooks.Open("H:\Integration Projects\Chk Req & Customer Payment Sheet\Chk Reqs\Check Request.xlsm", True, True)
ThisWorkbook.Worksheets("Sheet1").Range("B2:C2").Value = Source.Worksheets("Consolidated Summary").Range("C7:D7").Offset(Month(Date)).Value
Source.Close SaveChanges:=False
End Sub
I have the below code to open up files with variable file names, due to dates being in them. I personally save each file daily with the date stamp, ie this morning I saved a file with yesterday's date, 4.20.17.
This code will be run every Friday morning, and the goal is to load the last 5 work days' files (last Friday, this Monday, Tues, Wed, Thurs) grab some info out of those files (copy 2 cells from each), paste that info in a new sheet, and finally close each file.
Currently, the code is set to tell me when a file does not exist (for instance, last Friday was Good Friday, so Monday morning, I did not create any file for last Friday), and then ignore and move past that day.
The issue I currently have (besides the code being long and can probably be concatenated) is that a file exists for last Thursday, yet my code tells me there is none. I have been advised that this is because the code is actually looking at today (Thursday) and not a week ago Thursday, where there actually is a file.
Any assistance is appreciated. I removed a few days to make the below code less of a bear to look at, and a sample filename is "Agent Group Daily Summary 4.19.17"
Const strFilePath As String = "D:\Users\stefan.bagnato\Desktop\Daily Performance Summary\Agent Group Daily Summary "
Dim LastFridayDate, MondayDate, TuesdayDate, WednesdayDate, ThursdayDate As String
Dim fullFileNameLastFriday, fullFileNameMonday, fullFileNameTuesday, fullFileNameWednesday, fullFileNameThursday As String
Dim wbkLastFriday, wbkMonday, wbkTuesday, wbkWednesday, wbkThursdayOpen As Workbook
LastFridayDate = Format(Date - (Weekday(Date, vbFriday) - 1), "m.d.yy")
fullFileNameLastFriday = strFilePath & LastFridayDate & ".xls"
If Dir(fullFileNameLastFriday) = "" Then
MsgBox "File for last Friday doesn't exist!"
GoTo ExitLastFriday
End If
Set wbkLastFriday = Workbooks.Open(fullFileNameLastFriday, False, True)
Call BasicDailySummary
wbkLastFriday.Activate
Range("T2:T8").Copy
fp.Activate
Range("B3:B9").PasteSpecial xlPasteValues
wbkLastFriday.Activate
Range("F2:F8").Copy
fp.Activate
Range("G3:G9").PasteSpecial xlPasteValues
wbkLastFriday.Close SaveChanges:=False
ExitLastFriday:
MondayDate = Format(Date - (Weekday(Date, vbMonday) - 1), "m.d.yy")
fullFileNameMonday = strFilePath & MondayDate & ".xls"
If Dir(fullFileNameMonday) = "" Then
MsgBox "File for Monday doesn't exist!"
GoTo ExitMonday
End If
Set wbkMonday = Workbooks.Open(fullFileNameMonday, False, True)
Call BasicDailySummary
wbkMonday.Activate
Range("T2:T8").Copy
fp.Activate
Range("C3:C9").PasteSpecial xlPasteValues
wbkMonday.Activate
Range("F2:F8").Copy
fp.Activate
Range("H3:H9").PasteSpecial xlPasteValues
wbkMonday.Close SaveChanges:=False
ExitMonday:
....................................
ThursdayDate = Format(Date - (Weekday(Date, vbThursday) - 1), "m.d.yy")
fullFileNameThursday = strFilePath & ThursdayDate & ".xls"
If Dir(fullFileNameThursday) = "" Then
MsgBox "File for Thursday doesn't exist!"
GoTo ExitThursday
End If
Set wbkThursday = Workbooks.Open(fullFileNameThursday, False, True)
Call BasicDailySummary
wbkThursday.Activate
Range("T2:T8").Copy
fp.Activate
Range("F3:F9").PasteSpecial xlPasteValues
wbkThursday.Activate
Range("F2:F8").Copy
fp.Activate
Range("K3:K9").PasteSpecial xlPasteValues
wbkThursday.Close SaveChanges:=False
ExitThursday:
That a file exists for last Thursday, yet my code tells me there is none
As I explained in the other question you asked yesterday, putting the vbMonday or vbThursday etc in the Format function doesn't magically tell VBA to return that day:
Hint: The vbFriday part of the Weekday function is not magically telling it to get friday's date. It's actually telling it that, for the sake of this function call, consider Friday to be the first day of the week. The Weekday function then returns an integer (the ordinal day of the week) which it subtracts from the Date.
So, you need to go back and understand how those functions work, you can't just dump constants in there willy-nilly without making an effort to understand what they're doing, or why. On that note, you absolutely need to read this and learn how to begin debugging and troubleshooting first. This describes basics of how to step through your code and examine variable's values/etc at runtime. These techniques are foundations you need to work with VBA.
Here is a list of statements available in VBA. This is documentation that explains things like "How to create a loop structure with For/Next, etc."
And you should go back through the dozen or so questions you've asked here, and mark accepted answers for those where an answer has solved your problem. This is just a basic point of etiquette: You've asked 11 questions here and only accepted 1 answer.
Note also that this sort of declaration does not do what you think it does:
Dim LastFridayDate, MondayDate, TuesdayDate, WednesdayDate, ThursdayDate As String
Dim fullFileNameLastFriday, fullFileNameMonday, fullFileNameTuesday, fullFileNameWednesday, fullFileNameThursday As String
Dim wbkLastFriday, wbkMonday, wbkTuesday, wbkWednesday, wbkThursdayOpen As Workbook
Only the last item in each of those statements are strongly typed, the rest are implicitly variant. You should strongly type all variables when possible, e.g.:
Dim wbkLastFriday As Workbook, wbkMonday As Workbook, wbkTuesday As Workbook, wbkWednesday As Workbook, wbkThursdayOpen As Workbook
And rather than using five different workbook objects (unless you really need 5 workbooks open at once, just use a single workbook object and operate within a loop, opening successive file at each iteration.
Dim wb as Workbook
Dim i as Long
For i = 1 to 5
Set wb = Workbooks.Open(...)
'Do something
wb.Close()
Next
Getting to your actual problem:
A function like below will return an array of your date components. This returns the previous 7 days from the FirstDay (which defaults to Friday previous). You can use the Dir function as previously to simply test whether a filename is valid/existing (e.g., Sunday file doesn't exist, etc.), and skip over it if it's not valid.
Function GetFileNames(Optional FirstDay = vbFriday)
Dim filenames(1 To 7) As String
Dim i As Long
For i = 1 To 7
filenames(i) = Format(Date - (Weekday(Date, FirstDay) + i), "m.d.yy")
Next
GetFileNames = filenames
End Function
It seems that you want your search to start from yesterday instead of today. If so, you can try changing
ThursdayDate = Format(Date - (Weekday(Date, vbThursday) - 1), "m.d.yy")
into
ThursdayDate = Format(Date - (Weekday(Date - 1, vbThursday)), "m.d.yy")
and generalize it to other week days. In fact what it does now is that when it runs, say, on this Thursday, it looks up for the file of last Thursday...
I'm trying to automate a report that for a customer and I'm a bit stuck with one of the hurdles that needs to overcome, I have some ideas but am new to VB programming.
The requirement is to copy a range of cells from one sheet to another, but the destination needs to change depending on the current date. Using a general example I'm trying to achieve the following:
If the date is the 1st of the month, the destination range is B2:F3, if it is the 2nd then the destination range is B4:F5, if the 3rd then destination is B6:F7....... if the 31st then the destination is B62:F63, the source ranges are static.
I figured I could probably achieve this by writing a huge script which contained an IF statement for each day of the month, but I was hoping I could be a bit smarter and use variables to assign the row references at the beginning of the script then just sub them back into the select/copy statements.
Absolutely you can.
Dim x as Integer
Dim daymonth as Integer
Dim rw as String
daymonth = CInt(Format(date, "d"))
x = daymonth * 2
rw = CStr(x)
Now you can use range like:
Range("D" & rw & ":F" & CStr(x + 1))
Just an example. Then since the number is constant between the two ranges just add that number to x and use it in the range.
You may want following subroutine.
Sub copyDataDependOnDatte()
Dim today As Date, dayOfToday As Integer
Dim sWS As Worksheet, dWS As Worksheet
'set two worksheets to variables
Set sWS = Worksheets("source") 'Worksheet which has data to be copied
Set dWS = Worksheets("destination") 'Worksheet which is used to record data of days.
' get day of today
today = Now() 'get date of today
dayOfToday = Day(today) ' get day of today
Range(sWS.Cells(2, 2), sWS.Cells(3, 6)).Copy 'copy B2:F3 of worksheet "source"
dWS.Cells(dayOfToday * 2, 2).PasteSpecial ' paste to worksheet "destination" at place determined by day of today
End Sub
In this code,I assumed following for writing concreat code.
"source" is name of worksheet which contains the data to be copied
"destination" is name of worksheet which records tha data copied from "source" worksheet
Data to be copied is exist at "B2:F3" of worksheet "source"
Please change worksheets' names to real names of your data.
Place of data to be copied is described as "Range(sWS.Cells(2, 2), sWS.Cells(3, 6))" in the code.
cells(2,2) means cell on 2nd row and 2nd column, i.e. "B2".
Cells(3,6) means cell on 3rd row and 6th column, i.e. "F3".
Plese correct place to fit your data.
I need to copy some data every month, paste it into a spreadsheet and then save it as a new file with updated date. I need the macro to look to see if A6 is empty, then select all data from A6 down, which I think is done with the If Not statement.
Once done I need to open a spreadsheet that is saved in the format "Filepath/mmyy Filename.xls"
The sheet I need opening will be last months so I need it to select that month, and then the year in the format yy.
I will also need it to clear the sheet in a certain range and then paste in the data from the first workbook, then Save As with an updated date as mmyy with this months date.
How do I set my code to open the file based on mmyy, and then save as and close? And can this all be done in the IF statement I have opened?
Sub Test()
Dim wksht As Worksheet
Dim rng As Range
Set wksht = Sheets("Birse CH")
Set rng = wksht.Range("A5")
If Not IsEmpty(rng.Offset(1, 0)) Then
Set rng = Range(rng.End(xlDown).Offset(0, 14), rng.Offset(1, 0))
Selection.Copy
'opening workbook
Workbooks.Open Filename:="H:\Finance\CBF\Invoices\Monthly Invoicing Summary\" & Year(Date) & "\ASM\" & (Now(mm) - 1) & Now(yy) & " ASM CBF Reg Summary.xlsx"
Selection.Paste
End If
End Sub
What you're looking for is the Format function.
Format(Now, "mmyy")
returns 0914 at the time of writing.
However, it looks like you want to subtract one month from today's date. This will do the trick:
Format(DateSerial(Year(Now), Month(Now) - 1, 1), "mmyy")
which should replace (Now(mm) - 1) & Now(yy) which won't compile because that's not how Now works.
To SaveAs and Close, it's easiest to first set a reference to the workbook you're opening:
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:="...somewhere...")
'... do stuff to the workbook
wb.SaveAs Filename:="...somewhere else..."
wb.Close
I need to automate a process that's not a one-off event, ~500 facilities, each with 100+ assets which are all scheduled for different dates throughout the year for completion. I have a Workbook set up with my main/source sheet as well as 12 month sheets (Jan, Feb, March, ... Dec). What I need is some sort of code that would allow me to search for a particular date and send it as well as other same-row corresponding data to the appropriate sheet.
For example I have an asset that is due for maintenance in June, 6/17/11. I need for Excel to search for it using the month only, and moving that asset as well as it's name, description, cost, etc to the June tab. Ive managed to get it to locate assets searching for "6/" however it cannot find assets with a date of 6/17/11. It copies all needed data and attempts to move it to the proper sheet, when it makes this attempt a Microsoft Visual Basic error code 400 pops up. Any ideas? All help appreciated.
see if this helps ...
Private Sub FindCells()
'' step 1, find all the rows containing your date (June 2011 dates hardcoded in this example)
Dim CollectionOfRowRanges As New Collection
Dim ws As Worksheet
Dim rgCell As Range
For Each ws In ThisWorkbook.Worksheets
For Each rgCell In ws.UsedRange.Cells
If IsDate(rgCell.Text) Then
If Month(CDate(rgCell.Value)) = 6 And Year(CDate(rgCell.Value)) = 2011 Then
'' for debugging only ... watch and make sure it stops at the right places
ws.Activate
rgCell.Select
Stop
'' end of debug code
Call CollectionOfRowRanges.Add(rgCell.EntireRow)
End If
End If
Next rgCell
Next ws
'' step 2, copy the rows to a new wb
Set ws = Workbooks.Add.Sheets(1)
ws.Name = "June 2011 Rows"
Dim rgRow As Range
Set rgCell = ws.Cells(1, 1)
For Each rgRow In CollectionOfRowRanges
Call rgRow.Copy
Call rgCell.EntireRow.PasteSpecial(xlPasteValues)
Set rgCell = rgCell.Offset(1)
Next rgRow
End Sub