How to refresh calculation instantaneously in excel - vba

I have a problem in refreshing the cell's calculation.
In other words, I have many columns where i have a formula or macro in each one of them.
But the problem is that i should absolutely activate the option " automatic calculation" in the excel options or i should save then the new results appear.
Now, I would insert something in the macro that can refresh me the results instantaneously.
Thanks

To force all formulas to update, including custom vba formulas, execute the following in VBA:
Application.CalculateFullRebuild
This can also be executed from the VBA immediate window.
More documentation here:
https://learn.microsoft.com/en-us/office/vba/api/excel.application.calculatefullrebuild

You could simply press :
F9 to calculate the whole active workbook
Shift + F9 to calculate the active sheet
Anyway, here are the different options with .Calculate :
Sub Souma()
'Use this to calculate all the open workbooks
Application.Calculate
'Use this to calculate the whole sheet, called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Calculate
'Use this to calculate the cell A1 on the sheet called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Range("A1").Calculate
'Use this to calculate the range A1 to D10 on the sheet called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Range("A1:D10").Calculate
'Use this to calculate the column A on the sheet called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Columns(1).Calculate
'Use this to calculate the row 1 on the sheet called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Rows(1).Calculate
End Sub

Copy and paste the code below to your VBA project:
Private Sub Workbook_Open()
Application.Calculation = xlCalculationAutomatic
End Sub
This code should automatically run after you open the Excel file, enabling automatic calculation in all opened files.

Related

VBA - copy specific rows from one sheet into another sheet when user closes file

I'm new to VBA and I'm struggling a lot with a file I want to build.
I have a main Sheet that in a simple way looks like this (starting at column B - A is an empty column):
main
This is a simplified version just for the example. The first table of the sheet varies from B13 to O92, the second varies from B104 to O114 but some of those rows might be empty.
My goal is to join rows with content from the first area with rows with content from the second area in a different sheet (Sheet1), add to the left a column with 1s and "Cell 0" (content of cell B1). Using the example, the result would be something like this:
Sheet1
Sheet1 will stay hidden as I'm using it as a source of information to a different file. In fact, I may not need the 1s column if I find a way to copy information in a different way - I'm doing it like this (wsSource is Sheet1):
lRow = wsSource.Columns("A").Find(1, SearchDirection:=xlPrevious, LookIn:=xlValues, LookAt:=xlWhole).Row
wsSource.Range("B1:N" & lRow).Copy
I was trying to do it so Sheet1 is "emptied" when the file is opened and edited when file is closed - so that if new rows are added or information updated, it gets into Sheet1 every time.
I've tried several stuff I found online but couldn't make it to work. My main problem is adding the specified rows one after the others but I'm also struggling to reset Sheet1 every time the file is opened and automatically running the macro when file is closed.
Any help would be really appreciated.
Hopefully this will get you started. Both subs need to be pasted in VBE under ThisWorkBook rather module or sheet(n).
The first sub will execute when the workbook is open.
Are you sure you want to clear your sheet under these circumstances?
You will never have access to your table (without workarounds) since it will clear when opening every time.
If this is what you need, see the below method to clear a dynamic range (Col A - D down to last cell used in Col A) on Sheet1 every time the workbook that houses this code is opened.
Private Sub Workbook_Open()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim ClearRange As Range
Application.ScreenUpdating = False
With ws
.Visible = xlSheetVisible
.Range("A1:D" & .Range("A" & .Rows.Count).End(xlUp).Row).ClearContents
.Visible = xlSheetHidden
End With
Application.ScreenUpdating = True
End Sub
Next, the below sub will only execute before the book is closing. This is where the bulk of your code will go to build your table.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.ScreenUpdating = False
ThisWorkbook.Sheets(1).Visible = xlSheetVisible
'Code goes here
ThisWorkbook.Sheets(1).Visible = xlSheetHidden
Application.ScreenUpdating = True
End Sub
You will need to qualify your objects (Ranges, Cells, etc.) directly (which sheet) since the code will not be housed in a sheet. The first sub uses a With block to qualify ranges and the second sub directly qualifies all objects with ThisWorkbook.Sheets(1).
Lastly, I recommend writing your code to build your table inside a module (qualify ranges!) so you can test and debug without needing to close/open your book continuously. Once you have the code working in a module, you can copy and paste the code directly into the 2nd sub here and you are good to go!

Excel: Copy Dynamic Range from one worksheet to another

I am trying to copy a dynamic range (B12:Lxx)from one worksheet to another. I need the range being copied to stop at the first empty row (there is additional data further down the sheet which I don't want copied).
I am a very basic VBA user so if you could explicitly set out your instructions that would be handy.
Source: Worksheet "MyKPIs" with the dynamic range B12:Lxx (column L is set, row numbers are variable BUT must end at the first empty row)
Target: Worksheet "Month Template", cell B5
Trigger would be a command button
I have trawled through other articles but have failed to find anything that I could use.
Thanks,
Hayley
this will work. insert a command button on your worksheet. double click the button. paste in this code between sub and end sub.
Worksheets("MyKPIs").Range("b12").CurrentRegion.Copy Worksheets("Month Template").Range("b5")
it should look like this when you are through. then go to your worksheet on developer tab toggle off design mode then click the button.
Private Sub CommandButton1_Click()
Worksheets("MyKPIs").Range("b12").CurrentRegion.Copy Worksheets("Month Template").Range("b5")
End Sub
for those inexperienced with currentregion please look at the 2 samples below that have blank cells but the region is selected and you can easily see the beginning and ending points in the range and how an entire blank row or column forms the range.
Place a command button from the Forms toolbar on your "MyKPIs" sheet.
Then add this code:
Sub Button1_Click()
Dim myrange
Set myrange = Sheets("MyKPIs").Range("B12:L12")
myrange.Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy Worksheets("Month Template").Range("B5")
End Sub
Considering all cells in column B have data, this will copy all the cells in the range. It will stop at the first empty cell in column B. This should help you to start.

Secure Timestamp - VBA

I want to create a secure timestamp on my Excel sheet. The VBA I am using will automatically add the current users user name, the time, and the date when a user puts information into column A. So if the users puts something into cell A1 then B1 automatically gets filled with their username and C1 gets filled with the time and date. The only problem is that this method isn’t secure because the user could alter the information after it is automatically populated. I would like to add code to this VBA so it will lock all three cells after the information is populated.
I was planning on using the Protect Sheet feature and only allowing users to “Select unlocked cells” So if the VBA could auto lock the cells then the users would not be able to alter the information.
Moreover I have used Me.Unprotect before changing cells and Me.Protect after that still it is not working
Any help would be much appreciated!
Assume that we start with all the cells on the worksheet unlocked and the sheet password-protected with the password:
6LgSdHjc2uOssv0e1LDI
The following Event Macro will:
unprotect the workbook
detect entries in column A
place the username in column B and the date/timestamp in column C
lock the entries in columns A,B,C
re-protect the worksheet.
This goes in the Worksheet code area:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim A As Range, MyPass As String, sh As Worksheet
Dim unit As Range
Set A = Range("A:A")
MyPass = "6LgSdHjc2uOssv0e1LDI"
Set sh = ActiveSheet
If Intersect(Target, A) Is Nothing Then Exit Sub
Set unit = Union(Target, Target.Offset(0, 1), Target.Offset(0, 2))
Application.EnableEvents = False
sh.Unprotect (MyPass)
unit.Locked = False
Target.Offset(0, 1) = Environ("Username")
Target.Offset(0, 2) = Now()
unit.Locked = True
sh.Protect (MyPass)
Application.EnableEvents = True
End Sub
Because it is worksheet code, it is very easy to install and automatic to use:
right-click the tab name near the bottom of the Excel window
select View Code - this brings up a VBE window
paste the stuff in and close the VBE window
If you have any concerns, first try it on a trial worksheet.
If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx
To remove the macro:
bring up the VBE windows as above
clear the code out
close the VBE window
To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
To learn more about Event Macros (worksheet code), see:
http://www.mvps.org/dmcritchie/excel/event.htm
Macros must be enabled for this to work!

Excel 2010 VBA running in all opened files

I have one excel file (*.xlsm) with VBA code on first sheet:
Private Sub Worksheet_Calculate()
ActiveSheet.ChartObjects("Podtlak").Chart.Axes(xlCategory, xlPrimary).MaximumScale = Range("AV79").Value
End Sub
And second excel file with macro that is changing value in cell in first excel (it is automaticaly recalculated) and then copy value of new result from first excel and paste it to second excel file.
Problem is: when macro is going to second excel and paste value, worksheet is recalculated and code from first excel is calling, but it stops with error because in second excel it cant find chart object "Podtlak".
How to set worksheet_calculate() to run only for file whitch one is it written?
Try specifying the workbook:
ThisWorkbook.ActiveSheet.ChartObjects("Podtlak").Chart.Axes(xlCategory, xlPrimary).MaximumScale = Range("AV79").Value
Or specifying the worksheet and workbook:
ThisWorkbook.Worksheets("yourWorksheetName").ChartObjects("Podtlak").Chart.Axes(xlCategory, xlPrimary).MaximumScale = Range("AV79").Value
I like the 2nd option best as you are clearly specifying the worksheet and workbook that this function runs on. Anytime you use ActiveSheet or ActiveWorkbook, you are relying on the fact that your intended worksheet is active when the code runs.

How do I dynamically update the name of a worksheet in Excel?

I have an Excel spreadsheet which is being used to specify filesystem build information for our Unix team.
This worksheet would have different information depending on the system to be built. For example, a production system would have many filesystems, whereas a development system only one or two.
So based on user input, we would populate one or other of the two input worksheet formats ("dev","prod") but the destination worksheet will be always be the same. Only one of the dev or prod worksheets would be visible and active for users to input data at any given time.
How do we tell Excel to use a particular input worksheet to calculate another output worksheet?
My initial idea was that, for simplicity's sake, the "output" worksheet would take its data from an "input" worksheet, and that we would dynamically make either the "dev" or "prod" template become the "input" worksheet. Is this the right way to do this, or is there some better method?
There's a few ways depending on the complexity of the sheet:
If you only have a few worksheets, and users would just select "Production" or "Test", you could set up the conditional logic in the formulas. For example: =if(A1="Test",TestSheet!A1 + TestSheet!A2, ProdSheet!A1 + ProdSheet!A2)
You could utilize the same type of idea as above, but add more complexity using vlookup tables
Your VBA code could create the entire Excel spreadsheet dynamically based on the user input
if you can use VBA code as LuckyLindy suggests, you can do pretty much anything. What I used to do is record macros for various operations, for example adding or renaming sheets and take the generated code and adapt it to do exactly what was required.
An example of simple macro code:
Sub Macro1()
'
' Macro1 Macro
'
'
Sheets("Sheet1").Select
Sheets("Sheet1").Name = "My Sheet"
Sheets.Add After:=Sheets(Sheets.Count)
Sheets("Sheet5").Select
Sheets("Sheet5").Name = "My Sheet 2"
End Sub
You can record very complex operations and manipulate the generated code and place it behind specific events. So if you wanted the code to fire on worksheet load or activation of a sheet, you can insert it in the relevant block: i.e.
'in Sheet1 - code behind (alt+F11 shortcut)
Private Sub Worksheet_Activate()
Sheets("Sheet1").Select
Sheets("Sheet1").Name = "My Sheet"
Sheets.Add After:=Sheets(Sheets.Count)
Sheets("Sheet5").Select
Sheets("Sheet5").Name = "My Sheet 2"
End Sub
HTH
Another way would be to use the INDIRECT formula.
Say you have in cell A1 the name of the sheet you want to look up input from, then the following will look up the value of cell B7 from that sheet:
=INDIRECT($A$1,"!B7")