Set updated date on the active tab only - excel

I have done some things in SWIFT but this is my first project in VBA.
How can I set a field on an active tab to be the modified date of the tab? I have tried to use a Sub Workbook_open () procedure but this is my first attempt at VBA and after several ours of looking, I am no closer.
Some more detail: This workbook has multiple users who are assigned a specific tab. As their manager I need to know the last time they accessed their tab so I wanted to have that entered programatically. I have a "Reference" tab that holds variables and I have an updated date cell (D2) that is referenced on the individual tabs for each user.
Here is what I have tried but the debugger doesn't get passed the first line :(
`Private Sub Workbook_Open()
Dim Sheet As Worksheet: Set Sheet = ThisWorkbook.Worksheets("Reference")
Dim Entry As Range: Set Entry = Sheets("Reference").Range("D2")
Range(D2).Value = Date
'Debug.Print MyRNG.Value
Entry.Value = Date
End Sub`
Thank you in advance.

You can use the Worksheet_Activate event in the sheet module. It fires when a worksheet is activated. You can write code that puts a date/time stamp into a cell somewhere in the workbook.
Remember, this code goes into the Sheet module, not a code module.
Private Sub Worksheet_Activate()
' this writes just the date into the current sheet's cell A1
[A1] = Date
' this writes the date and time into A1 on Sheet2
ThisWorkbook.Worksheets("Sheet2").Range("A1") = Now
End Sub
Be aware that this code fires when ANYONE activates the sheet. If you want to log activities of specific people only, then you need to add more refinement.

Related

How can I "generically" select worksheets from a script

I am writing a script for a workbook that is to be used by multiple departments. The button click imports a weekly report to a master data worksheet, creates a new sheet/Tab, asks what to name that new worksheet (Which will be the week date the report references.), place an MS Query table onto the new sheet, filtered from the master, clears the master sheet and prepares the work book to repeat the same thing when the next weekly report gets added (...and is all working at the moment.). The next time someone updates the workbook, it will the button click to again use the same script to add yet another worksheet for the new week and so on, but, since I started from recorded macros to writing the rest of what I need, everything in the script is referencing the first new worksheet by worksheet name, Like this example:
Application.Goto Reference:="W11_9_2020"
Sheets("W11_9_2020").Select
Range("A1").Select
Here (Above) I would like this to be a generic reference to the latest sheet in the script, not the exact name so it is reusable the next x amount of times the workbook gets updated.
The next time someone updates this, it will still add a new sheet, but once it gets to the part where the query table is created and the new sheet is formatted, data added, blah blah, it's just going to repopulate the first sheet again since it used that sheet name in the script (Or error out).
I tried using:
Set Worksheets(Worksheets.Count) = wsDest1
wsDest1.Range("I1").Select
ActiveCell.FormulaR1C1 = "Week"
wsDest1.Range("J1").Select
ActiveCell.FormulaR1C1 = "Total Shipped"
wsDest1.Range("K1").Select
ActiveCell.FormulaR1C1 = "Total On Time"
wsDest1.Range("L1").Select
ActiveCell.FormulaR1C1 = "Total Late"
wsDest1.Range("L2").Select
..in the hopes of generically using a reference to the latest added worksheet (Which is always "Add after") but doing that brings an error stating that it is an illegal use of a procedure and highlights this line -->> Set Worksheets(Worksheets.Count) = wsDest1.
I guess in trying to write this for unlimited reuse, I would like the sheet references to be variables or something so it always references the latest added sheet before the button click would add another and repeat/rerun the same script for any given new update.
Is there another way to generically(?) identify the latest sheet/tab in the body of the script without the exact sheet name being identified?
Keep in mind that the method to add a new worksheet also returns a reference to that worksheet. So, create the reference when you create the worksheet, and then refer to it later.
Sub AddSheet()
Dim sheetName As String
Dim wsNew As Worksheet
'Get the sheet name, however you're currently doing it
sheetName = "NewSheet"
Set wsNew = Worksheets.Add()
wsNew.Name = sheetName
'Do the rest of the stuff
wsNew.Range("A1").Value = "Hello"
End Sub

How to copy and paste an existing .xlm workbook file ona certain date and time without opening the existing file?

How to copy and paste an existing .xlm workbook file automatically on a certain date and time without opening the existing file?
I have a vba workbook file which I use to record certain data monthly. At the end of the month I must save this workbook and start a new workbook file by copying the existing file and thereafter I manually revise certain data ( such as dates, names, figures etc.)before I start using it again to record my usual daily data.
I would like to have copy-paste-revise actions automatically at a certain date and time: for example 1st of the new month at 07:00 AM.
I will appreciate any suggestions on how to go about it?
Thanks
SATAMAN
Here is the basic structure of code which will run not at a specific time but after it. In fact, it runs whenever the workbook is opened but takes no action until a certain date has passed. This is an event procedure. It must be copied to the ThisWorkbook code module. It's designed for testing and tested. Run it on a blank worksheet with a date in A1.
Private Sub Workbook_Open()
' "TestCell" is the cell in your worksheet that contains
' a date that is updated to the current month when this program runs
Const TestCell As String = "A1"
Dim TestRng As Range
Dim Test As Variant
' "Sheet1" is the CodeName of the "Monthly Data" tab
' it remains the same whichever tab name the user gives.
' Change the CodeName in the Properties window.
With Sheet1
Set TestRng = .Range(TestCell)
Test = TestRng.Value
If IsDate(Test) Then ' skip if no date
If Month(Test) < Month(Date) Then ' skip if date is in this month
' this presumes that you will want the same action
' even if Test is more than a month ago.
' If not, you can separate ways at this point.
With ThisWorkbook
' This command creates a copy of this workbook under
' any name in any location while keeping ThisWorkbook
' open and in its original location.
' This means that the current workbook always retains
' its name and copies are renamed to reflect the period
' they cover. You might also strip copies of their code
' by changing the file format.
' You might adapt your naming conventions to such a system.
.SaveCopyAs Environ("UserProfile") & "\Desktop\" & .Name
FormatWorkbookForNewMonth CDate(Test), TestRng
End With
End If
End If
End With
End Sub
Private Sub FormatWorkbookForNewMonth(ByVal LastDate As Date, _
TestRng As Range)
Dim Ws As Worksheet
Set Ws = TestRng.Worksheet
' do the changes to the workbook here
TestRng.Value = DateSerial(Year(Date), Month(Date), 1)
End Sub
You should have one cell on your worksheet on which other dates, such as dates in captions, in your worksheet are based. Once this date changes the meaning of the sheet changes with it. Such a cell is ideal for identifying whether a change has taken place and even what that change was. In the code above I have designated A1 - easy to change in the code. The event procedure simply checks if the date is in a previous month and jumps into action when it isn't.
The present procedure creates a copy of the file (on your desktop for now) and resets the date in A1 to the first day of the current month. So, if the same procedure is run again no action will be taken until the month changes.
BTW, although this is an event procedure which is triggered by the Open event, you can actually run it on F5 as well.
There is no direct way in VBA to schedule a Macro for a specific date. You can use Application.OnTime to trigger a macro at specifed time.
You can either create an Exe and add it to Windows scheduler or Check for date in your macro and call the macro by resetting Application.OnTime.
Sub MyProc()
If Day(Now) = 1 Then
' Execute the proc
End If
' extend procedure schedule by a day
Application.OnTime Now() + TimeValue("24:00:00"), "MyProc"
End Sub
src: https://p2p.wrox.com/excel-vba/72435-schedule-excel-run-macro-specific-time-date.html#post233865

Naming a Cell in Excel

I'm trying to create a series of macros to audit some financial models.
The first macro I’m trying to create is one that names the current cell. Why? I want to name the cell, after that I’m going to record a macro to click the “Trace Precedents” and go to the cell that has the relationship.
After that I need to go back to the original cell, thats the named one. That's easy on the go function, but I need to the naming macro working
My recorded code for the naming macro is as follows:
Sub Namer ()
ActiveWorkbook.Names.Add Name:="Name1", RefersToR1C1:="=Workings!R42C6"
ActiveWorkbook.Names("Name1").Comment = ""
End Sub
I have the following problems:
I need to name the current cell on a workbook with a lot of sheets. I’m gonna be moving between sheets but my recorded code has a “fixed” sheet.
How can I fix that? Name the current cell on the current sheet
Something like this should help you ...
Public Sub CreatesNames()
Dim objSheet As Worksheet
For Each objSheet In ThisWorkbook.Worksheets
objSheet.Names.Add Name:="Name1", RefersTo:=objSheet.Range("A1")
Next
End Sub
... something to note, names can be created at the worksheet level or at the workbook level, so, if you're going to be creating the same name across worksheets then you need to use a Worksheet object, not the Workbook object.
So to use the active cell ...
Sheet Level
ActiveSheet.Names.Add Name:="Name1", RefersTo:=ActiveCell
Workbook Level
ActiveWorkbook.Names.Add Name:="Name1", RefersTo:=ActiveCell
I hope that helps.

I want to read data from two excel sheets to one excel sheet with button using VBA?

enter image description hereI want to read data from two sheets whereas user will enter only date and after clicking button data will be populated in sheet.
Title Date
Enter Week Start Date "7/11/2016" (Button)
Name Project-ID Project Name Project Start Date Project End Date Sum Sum * 20
This is actual format of requirement.
in your line
Set objsheet = bjExcel.ActiveWorkbook.Worksheets("Config_InputAllocation_Weekly")
Set objsheet2 = objExcel.ActiveWorkbook.Worksheets("Config_Project")
you try to set both sheets active, which is not possible. There only be one active sheet. But you don't have to set them active. Use the following technique:
Dim objExcel as Object
Set objExcel = CreateObject("Excel.Application")
Dim myWb as workbook, myws1 as worksheet, myWs2 as worksheet
Set myWb = objExcel.Workbooks.Open("C:\Users\ABC\Documents\NSL\Automation Macro\NSL_DM_Tracker.xlsm")
Set myWs1 = myWb.Worksheets("Config_InputAllocation_Weekly")
Set myWs2 = myWb.Worksheets("Config_Project")
Then you can easily call the data from both sheets whether they are active or not:
Msgbox myWs1.Cells(1,1).value
Msgbox myWs2.Cells(1,1).value
Then the other problem is that you have defined an Sub searchdata() but it is not called within your CommandButton1_Click() Sub.
Moreover use Option Explicit setting, that is, put this line at the very top of your code:
Option Explicit
This will help you to debug your code.
Last but not least, in your Sub searchdata() no Worksheets are defined. Thus it will not know which one (myWs1 or myWs2) to use and when.
Good Luck,
Viktor

VBA to check if last cell equals cell on different sheet

I have a spreadsheet that is used to log information. In one sheet you enter the data then VBA updates a second sheet where the info is stored.
I want to write a code that will check if a cell on the last row of the log (which will be changing as it updates each time) equals a cell on the input page.
The aim is to stop someone updating the log twice, I already have an alert that it has been updated but want to put a foolproof system in place to stop an entry being logged twice.
I am new to VBA so do not really know where to start.
The below is an example of achieving this. I have added comments to explain what is happening in the VBA.
In Excel, press Alt+F11
In the project window on the left, expand it if its not already and
double click on 'ThisWorkbook'
If it is not already there, type Option Explicit as the first
thing in the main window. This means the code will not run unless
all variables that are used are declared, this is good practice
Past the below code into the window
With the cursor in the code you can press F8 to run it line by line
to see what is happening or F5 to run it in one go.
You will want to adjust it to your required workbooks, worksheets, and cells/columns.
Public Sub Sample()
'Clearly declare variables, in the case we are using them
'to reference a workbook and a worksheet
Dim WkBk As Workbook
Dim WkSht As Worksheet
'Set the WkBk variable (which was declared as a workbook,
'which means it can only be used for workbook objects.
'I this instance we are refering to ThisWorkbook,
'which is as it sounds.
Set WkBk = ThisWorkbook
'We can now make a reference to a specific worksheet
'within our referenced workbook
Set WkSht = WkBk.Worksheets("Sheet2")
'This IF statement is comparing the value of cell
'A1 on Sheet1 to the the value of the last populated cell
'in column A of Sheet2 (the sheet we created a reference to)
If WkBk.Worksheets("Sheet1").Range("A1") = WkSht.Range("A" & WkSht.Rows.Count).End(xlUp) Then
MsgBox "It was a match"
End If
Set WkSht = Nothing
Set WkBk = Nothing
End Sub

Resources