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.
Related
I have a VBA code in a sheet that is activated when a cell is changed. But this sheet is re-created by another macro, and when the sheet is re-created it does not have the VBA code inside the sheet.
Then I was looking for two solution (I don't know how to do it and did not find anything on the web, then I ask here):
a way to automatically copy and past the VBA code so the the new sheet created by the macro will have the VBA code
or call the VBA code that can be stored in a module (don't know even if it is possible, since is "Private Sub Worksheet_Change(ByVal Target As Range)")
Just to clarify better, below the VBA code that is inside the sheet that is re-created by a macro
Public Sub Worksheet_Change(ByVal Target As Range)
Dim sht As Worksheet
Dim LastRow As Long
Dim isect As Range
Dim firstCell As Range
modulo = ActiveSheet.Offset(-1, -3).Value
tipo = ActiveSheet.Offset(-1, -2).Value
nome = ActiveSheet.Offset(-1, -1).Value
descrizione = ActiveSheet.Offset(-1, 0).Value
Worksheets(modulo).Activate
Range(A1).Select
With ActiveSheet
.Range("A1:E10000").AutoFilter Field:=1, Criteria1:=modulo
.Range("A1:E10000").AutoFilter Field:=2, Criteria1:=tipo
.Range("A1:E10000").AutoFilter Field:=3, Criteria1:=nome
ActiveSheet.UsedRange.Offset(1, 3).SpecialCells(xlCellTypeVisible)(1).Value = descrizione
End With
UserForm3.Show
End Sub
Thanks!
a) For an example on how to copy code see Copy VBA code from one Worksheet to another using VBA code
b) You can copy code, but you need to set "Trust Access To Visual Basics Project". How to do so, see https://stackoverflow.com/a/11680865/7599798. Be aware that this is an individual setting (per user) and therefore you cannot be sure that this works for all user.
c) Your attempt to put the code into a module will not work. Event routines need to be in the Workbook/Worksheet where the event happens. If the new sheet is copied into a Workbook where you have already code, you could use the
Workbook_SheetChange event which is triggered at any change on any sheet within the workbook.
d) If the (re)creation of the sheet is done by a macro that you control: Instead of adding a new sheet, copy an existing template sheet that already contains code.
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.
i m new to vba and try to write some code copying some group data from a protected workbook to new Workbook.
In my source sheet is a list of grouped data with some columns like COUNTRY, REVENUE, WIN, LOSS.
The entity of country is grouped by region.
So under ever country is variable number of regions with subRevenue, subWIN, subLOSS.
What I expect: for a defined group of country entities (eg. GERMANY and JAPAN) I want to copy these data with its subdata (regions) to new Workbook.
May anyone provide me a generic example or useful functions?
Thank you in advance! (a VBA Noob)
So here something to start you off with.
First since the sheet is protected you'll need to unprotect it before being able to copy anything. The below code shows you how to do that and uses strPassword as a variable containing the password. Since the sheet is already protected in your case you'd start with unprotecting it, then doing your copying operation and then protecting it again.
In General you can use range.copy with range.pastespecial to copy data wherever you wish. To copy to a new workbook you can use Workbooks.add otherwise just specificy the filepath of the other workbook
Sub YourSub()
Dim ws As Worksheet: Set ws =Worksheets("YourSheet")
Dim strPassword As String: strPassword = "YourPassword"
Set NewBook = Workbooks.Add ' OR the workbook path
ws.Unprotect Password:= strPassword
ws.Range("A1:AA100").Copy
NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
NewBook.SaveAs FileName:= ' Insert FilePath/ FileName here
ws.Protect Password:= strPassword
End Sub
This is some general information about how you would be going about copying ranges from a protected workbook to another workbook. To do this for certain countries you could create a table or use named ranges(using name manager or in VBA itself). Then you can adress the specific ranges either using if.. elseif.. else.. end if or the select case method, with your list of cases pointing towards a range containing all the countries to be copied.
Hope this was helpful as a quick overview
I am trying to copy an excel worksheet into another excel workbook. This generally wouldn't be too difficult, except I am moving my worksheet into a workbook that is saved using variables.
Here is a bit of my code:
Sheets.Add After:=Sheets(Sheets.Count)
ActiveCell.FormulaR1C1 = "a"
Sheets("Policy Search").Move After:=Workbooks(fname).Sheets(SheetName)
"policy search" will always be named the same, and this is the workbook I am trying to move. However, I am trying to move it to a file that is dynamically saved using the variable "fname", and the sheet name "SheetName".
Every time I try and run this bit of code, I am getting a Subscript out of range error. Any ideas on how to fix this?
Thanks!
Try this:
Sub MoveSheet()
Sheets("Policy Search").Select
Sheets("Policy Search").Move After:=Workbooks(fname).Sheets(SheetName)
End Sub
It assumes "Policy Search" is the active 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