Record values from if Statement to current Cell Excel - excel

I have created and excel spreed sheet.
Its pulls External data from a website into sheet 1.
On Sheet 2 Is where all my calculations are done.
In Sheet 2..
B1 is my Current Value that updates every hour,
M1 Is my current Time,
F1 Is my Current Time,
A4:A27 Is my Date Range,
B3:Y3 Is my Time Range,
And I'm using an if statement.=if(AND(F1=A4:A27), (M1=(B3:y3),B1,"")
If statement works fine. See image Below.
You can see on the 20-11-2017 there is a value under the 7 on today date. When the time changes to 8 the 7 value disappears. As see in the second image below. Because of the if statement not being true on the 7 value any longer.
I'm looking to store the history of the passed values.
How can i allow the if statement to save the values as a value instead of a reference that keeps changing.

You can use the Worksheet_Change Event with the following code. Basically it checks for the cell which is changed, if the cells changed is the "Current Value" cell then it will update the related date / time cell in the table.
Just double check your cell references in code below.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
'If the changed cell is the Current Value cell
If Target.Address = "$B$1" Then
Dim LastRow As Long
Dim DateRange As Range
Dim TimeRange As Range
'Can change the sheet name to what ever your final sheet will be called
With Target.Worksheet
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
Set TimeRange = .Range("B3:Y3").Find(Hour(.Range("K1")))
Set DateRange = .Range("A4:A" & LastRow).Find(.Range("F1"))
.Cells(DateRange.Row, TimeRange.Column).Value = .Range("$B$1").Value
End With
End If
End Sub

What you are looking for is TrackChanges. Excel has a native TrackChanges functions, that when needed, can export the history like you wanted, to a seperated sheet.
The downside is, however, you have to share it. More information can be found here:
Track changes in a Shared Workbook
Important: This article explains an older method of tracking changes using a "Shared Workbook." The Shared Workbook feature has many limitations and has been replaced by co-authoring. Co-authoring doesn't provide the ability to track changes. However, if you and others have the file open at the same time, you can see each other's selections and changes as they happen. Also, if the file is stored on the cloud, it's possible to view past versions so you can see each person's changes. Learn more about co-authoring.
If you want to go with VBA route, you can make a sub to copy every newly data added to the worksheet whenever it changes ( event-trigger sub )
Private Sub Worksheet_Change(ByVal Target As Range)
' Do stuff when worksheet changes
End Sub
An example is this: How do I get the old value of a changed cell in Excel VBA?

Related

Combine new dynamic array features of excel with VBA

I tried to work a bit more with dynamic arrays in excel in combination with vba. My problem is that I cant return a table-column with vba. Here a minimal example of what I want to do:
I have two Tables TabFeb and TabMar (see image below). Each of them has a column costs which I want to sum up individually. The results shall be put into a new Table. This can be easily done in excel with =SUM(TabFeb[Costs]) and =SUM(TabMar[Costs]), respectively. My idea is now to write a VBA function which takes a string as input, in this example it will be the month, and returns the table acording to the input. After that it will be summed up and the result is given in a cell.
I tried the following:
Function Selectmon(mon As String) As Range
If mon = "Feb" Then
Set Selectmon = Worksheets("Sheet1").ListObjects("TabFeb").ListColumns("Costs").DataBodyRange
ElseIf mon = "Mar" Then
Set Selectmon = Worksheets("Sheet1").ListObjects("TabMar").ListColumns("Costs").DataBodyRange
End If
End Function
The problem of this idea is that this function just copy the table data. Hence, if I would change the input table data the sum would not change. One has to recalculate every cell by hand. Somehow I need VBA to return TabFeb[Costs] for the input "Feb". Does anyone have an idea how this can be done?
Example
It's really just a one-liner (unless you want to do some in-function error checking)
Function Selectmon(mon As String) As Range
Set Selectmon = Range("Tab" & mon & "[Costs]")
End Function
As implied by #ceci, this formula will not update with changes in the table. Depending on other particulars of your worksheet, you can have it update either by
embedding it in a worksheet change event code;
or by adding the line Application.Volatile to the function itself.
The latter method will force a recalculation when anything changes on the worksheet that might cause a recalculation.
The first method can limit the recalculation only when there has been a change in the data, but has other limitations.
One of the limitations of the Worksheet Change method is that it will only work on the relevant worksheet.
If you use the Workbook sheet change method, you won't have that limitation.
In either event you can limit your code to run only when the table has changed.
Here is one generalized method:
Option Explicit
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim LOS As ListObjects
Dim LO As ListObject
Set LOS = Sh.ListObjects
For Each LO In LOS
'could select relevant tables here
'Could also select relevant worksheets, if you like
'for example
Select Case LO.Name
Case "TabFeb", "TabMar", "TabApr"
If Not Intersect(LO.DataBodyRange, Target) Is Nothing Then
Application.EnableEvents = False
Application.Calculate
End If
End Select
Next LO
Application.EnableEvents = True
End Sub
And there is other code you could use to find the relevant formula and just update that formula -- probably not worth the effort.

How to change a cell value based on active/selected cell

I am having a list of names in a Range A2:A77, in the worksheet name called Manual. whenever i choose a name, that is when a cell gets selected from the range, that active cell value should get reflected in the cell C1. Also, the macro should not work incase if i selected else where, other than the given worksheet or range.
I have googled alot but nothing seem to be matching my criteria, so i'm here, hoping for a better solution. You may ask me to achieve this by using data validation, but for that i will have to do multiple clicks and scrolling work to be done everytime. so to avoid that i'm looking for vba code to minimize the work and time.
Thank You.
I am only just learning VBA at the moment so this could be some very horible code but here goes.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cells As Range
Set cells = ActiveSheet.Range("A1:A27")
If Not (Intersect(Target, cells) Is Nothing) Then
ActiveSheet.Range("C1").Value = Target.Value
End If
End Sub
Worksheet_SelectionChange is called if the selected cell in the sheet changes then using the test from InRange that I found here: VBA test if cell is in a range test if the cell is within the defined range then set the values.
Edited as sugested by #Vitaliy Prushak in comments.

How to update cell references when moving cells into same sheet as target?

How do you force an excel workbook to use itself as a source for worksheet links?
I'm writing a VBA macro to automate the process of adding an excel worksheet into a workbook. The worksheet (sheet1) takes only certain (but very many) responses from within the several sheets (response1, response2, response3) of the questionnaire. As a result of this, sheet1 contains lots of cell references that don't lead anywhere until after the macro is run.
For instance a1 in sheet1 "='response1'!b6". This returns a #REF! error before the macro is run (which is fine).
After the macro is run sheet1 is now inside the correct workbook, and "='response1'!b6" is now a valid cell reference.
Except excel doesn't realise this until after I manually click the cell in Sheet1, press f2, then press enter. When I do this the cell is correctly populated. The trouble is there are large numbers of cells.
Is it possible to construct a VBA macro that will simulate this process of selecting formula boxes and pressing "Enter". Looking up people with similar problems, most have had the problem remedied by some combination of f9, turning automatic calculation back on, or ActiveSheet.Calculate or a variant. None of these have worked, it appears to be an issue with references, even though the references point to valid locations.
Otherwise, is it possible to use VBA to perform the same process as:
Data > Edit Links > Update Values
But in this case we'd need to specify the currently opened workbook as it's own source. Is there any way to do this?
When I manually selected the current workbook as the source under "Edit Links > Update Values" excel strangely repeats the worksheet name in the cell references, like this: "='[response1]response1!B31", which then fails to update when cell b31 changes, so this is not a solution.
Here's the code that runs on button press:
Private Sub CommandButton1_Click()
'copy worksheet into responses
Dim CopyFromWbk As Workbook
Dim CopyToWbk As Workbook
Dim CopyToWbk As Workbook
Set CopyFromWbk = Workbooks("Addition.xlsm")
Set ShToCopy = CopyFromWbk.Worksheets("Sheet1")
Set CopyToWbk = Workbooks("QuestionnaireResponses.xlsm")
ShToCopy.Copy After:=CopyToWbk.Sheets(CopyToWbk.Sheets.Count)
Workbooks("QuestionnaireResponses.xlsm").Activate
'Put code to update links in here
ThisWorkbook.UpdateLink Name:="myfilepathgoeshere.QuestionnaireResponses.xlsm", Type:=xlExcelLinks
'End update links
Thanks for any help, this one's a head scratcher.
Great idea from #Kyle. For those who having trouble forcing cell references to update, TextToColumns works.
However TextToColumns draws an error if the source range is empty, so if there's any chance of that being the case use an if statement with no action attached to skip over those instances.
My successful code looks like this:
Dim i As Integer
For i = 1 To 1004
'Scans through row 2 from col A onwards
'If cell is empty, does nothing.
'If cell is not empty, performs TextToColumns where source range = target range.
If IsEmpty(Workbooks("QuestionnaireResponses.xlsm").Worksheets_
("response1").Cells(2, i)) Then 'Does nothing if the cell is empty.
Else
Workbooks("QuestionnaireResponses.xlsm").Worksheets("response1").Cells(2, i).Select
Selection.TextToColumns Cells(2, i) 'Performs TextToColumns
End If
Next
All of my data is on the same long row. To apply the above to an entire spreadsheet, just nest everything between, and including, For i = 1 and Next within another For loop with different letter replacing i.

Excel sheets dependant on / mirroring each other

Let's say I have three sheets in Excel. Sheet 1 is the Master sheet, sheets 2 and 3 contain different sets of information with the same headers that feed into the table in the master sheet. Is there a way to make it such that I could edit information in sheet 1 and sheet 2 will change AND vice versa so I can edit info in sheet 2 that will update the master sheet?
You could solve it by having Vlookup-formulas in your Master sheet. That way, if you change anything in sheet 2 and 3 the Master will automatically be updated.
If the user changes anything in the Master sheet, you will have to build logic in VBA on that. One way to go is to format the Master sheet so that there is something that helps the VBA know what the formula should be in the edited cell, and also to know from where the data should come. Loosely one could set up the Master sheet like this:
Row 1 is hidden and contains the template formulas
Row 2 is hidden and is completely empty (this will make less problems with filtering)
Row 3 contains headers
Row 4 and down contains the data, using the formulas define in row 1
Add the Change event on the Master sheet, that sees if the changed cell was one with a formula. If so, it will examine the template formula to identify from where the data should come. Then it will update that cell in Sheet 2 or 3 with the new value that is entered in the Master sheet. After this, it will overwrite the value manually entered in the Master sheet with the formula from the template row.
The big job here is to write a parser that understands from which cell the vlookup will get it's value.
One thing that I overlooked is that the CHANGE event is triggered only ONCE if the user pastes several cells in one go. The TARGET will then contain several rows or columns.
So this is some kind of skeleton using the above idea...
Option Explicit
Dim ChangeEventDisabled As Boolean 'Flag for disabling the Change event
Public Sub Disable_ChangeEvent()
ChangeEventDisabled = True
End Sub
Public Sub Enable_ChangeEvent()
ChangeEventDisabled = False
End Sub
Sub Worksheet_Change(ByVal Target As Range)
Dim updatedValue As Variant
Dim SourceCell As Range
'While the MasterSHeet is populated intially, we don't want this event to do anything
If ChangeEventDisabled Then
'There are chenges being done in teh sheet that should not trigger updates of the source-sheets.
Else
'Only run the code if it was a data-cell that was changed
If Target.Row > 3 Then
'We are in the rows containg data
'Did the changed cell contain a Vlookup formula before the user changed the cells value?
If UCase(Cells(1, Target.Column).Formula) Like "=VLOOKUP(*" Then
'A vlookup normally populates this cell.
'To know from where the data normally comes, I will need to put back the formula in the changed cell.
'So, first save the new value that we will write in the source cell
updatedValue = Target.Value
'Insert the formula again in the cell
'As we will now CHANGE a cell in the Masterr sheet, a Change event will trigger. Disable it temporarily
Disable_ChangeEvent
Cells(1, Target.Column).Copy Destination:=Target
Enable_ChangeEvent
'Find out from which cell the data is being fetched by the Vlookup
Set SourceCell = MyMagicParsing(Target)
'Update the source-cell with the new value
SourceCell.Value = updatedValue
End If
End If
End If
End Sub
Function GetSourceCell(Target As Range) As Range
'This function should decipher the formula in the cell Target, and figure out from where
'the data is actually coming. It shoudl return the range which is the source of the data.
'As I dont know how to do that quickly, I just hardcode the cell that is the source.
GetSourceCell = Worksheets("Sheet2").Cells(67, 3)
End Function

Moving Rows to another sheet in a workbook

I need Help!
I am not well versed in VBA or Macros but i cannot find any other way to accomplish what i need to do without using it.
I have a sheet which i will be using to track Purchase orders, and what i need to do is; when i have a row in sheet 1 (Purchase Orders) which has been recieved i.e. the date of receipt has been recorded in column H i need for the entire row to be cut and pasted into sheet 2 (Received orders).
The header takes up the first 7 rows the rows, so i need the macro to look at rows 8-54. Once the received items are removed from sheet 1, i need the row to also be deleted or preferably for the list to be sorted by column A moving the now empty row which has been cut from open for a future entry.
Any help would be greatly appreciated.
The "Record Macro" feature should be enough to do the task you describe.. In Excel 2007, go to the Developer tab in the Ribbon, and select "Record Macro", and perform exactly the steps you are describing. It will record the equivalent VBA code, which you can then execute - or tweak/modify.
I tested this out, here's one way to do it:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Dim receivedDate As Range, nextOpen As Range, isect As Range
Set receivedDate = Sheet1.Range("H8:H54")
Set isect = Application.Intersect(Target, receivedDate)
If Not (isect Is Nothing) And IsDate(Target) = True Then
Set nextOpen = Sheet2.Range("A1").End(xlDown).Offset(1, 0)
Target.EntireRow.Copy Destination:=nextOpen.EntireRow
Target.EntireRow.Delete
End If
Application.EnableEvents = True
End Sub
This would be pasted into the Sheet1 code. Any time a cell is changed on sheet1, the code checks to see if it's in the critical range that you specified. (H8:H54) If it is, it then checks to see if it's a date. If it is, it then copies the entire row, puts it in the next open row on Sheet2, and deletes the original row. The cells below it will get shifted up so there are no gaps.
Since the code functions on a cell changing event, it disables "Application.EnableEvents" in order to avoid a loop of changing a cell to call an event which changes a cell to call an event... etc.

Resources