I'm trying to filter out all but todays date using a macro (for the first time)
I want to create a macro or two that will show only rows using the date in which it's viewed. I've tried using the below, but it hides all rows containing a date
Dim cell As Range
For Each cell In Range("A10:A1000")
If cell.Value <= Date Then
cell.EntireRow.Hidden = False
End If
Next
End Sub
Basically you don't need VBA to achieve this: you could use the filter functionality of Excel.
But if you want to do it via VBA this is a routine that does what you want:
Option Explicit
Public Sub hideRowsIfNotDate(rgToCheckDate As Range, dateToBeVisible As Date)
Dim c As Range
For Each c In rgToCheckDate.Cells
If IsDate(c.Value) Then 'just to be on the safe side if there is no date
If c.Value <> dateToBeVisible Then
'hide rows with different date
c.EntireRow.Hidden = True
Else
'show rows that match the date - just in case they were hidden before
c.EntireRow.Hidden = False
End If
End If
Next
End Sub
Advantage of this solution:
you can pass different dates or ranges, therefore you can reuse the sub for different scenarios
when you call the sub from your main code you simply know by reading the subs name what it is doing (w/o reading the code itself) - someone else (or you in 3 months) will appreciate that :-)
You will call the routine from your main code like this:
Public Sub test_hideRows()
Dim dateToBeVisible As Date
dateToBeVisible = Date '= today
Dim rgToCheck As Range
Set rgToCheck = ActiveSheet.Range("A10:A1000")
hideRowsIfNotDate rgToCheck, Date
End Sub
Have you tried AutoFilter? I assume that your data are stored in Rows("10:1000"), dates - in the column A and you have some headers in Rows(9). With that in mind:
Set Source = Rows("9:1000")
Field = Range("A:A").Column
Value = Format(Date, Range("A10").NumberFormatLocal)
Source.AutoFilter Field, Value
If you have a custom date format, put that instead of ...NumberFormatLocal
Related
I am trying to create a macro that will first allow the user to easily transfer data to another sheet based on a dropdown list to select the month. I want the user to able to enter the date in the field I have created, then use buttons on the sheet to first select which month to paste though, then confirm the paste. I have twelve named ranges from Ref_Jan to Ref_Dec on a sheet named "DB - Ref Monthly" I am working on putting together the pieces but I'm stuck here with my test program:
Sub Button8_Click()
Dim MonthSelector As Range
Dim Ref_May As Range
If Range("MonthSelector") = Range("Ref_May") Then
Sheets("DB - Ref Current").Range("Ref_Current").Copy
Sheets("DB - Ref Monthly").Range("Ref_May").PasteSpecial xlPasteAll
Application.CutCopyMode = False
Application.ScreenUpdating = True
Else
End If
End Sub
My current plan is to use 12 if statements to refer to each month, as I already have the copy/paste portion of the code working in another sheet. If I am going about this all wrong I would not mind some guidance. Please let me know if I have been unclear and can provide additional information.
Use looping to iterate months then no need to duplicate a code logic.
Dim arrMonth As New Collection
Dim idx As Integer
Dim val As String
Call arrMonth.Add("Jan")
Call arrMonth.Add("Feb")
Call arrMonth.Add("Mar")
'..etc..
Call arrMonth.Add("Dec")
For idx = 1 To arrMonth.Count
val = arrMonth.Item(idx)
Call MsgBox(idx & "=" & val)
Next
Assuming Range("MonthSelector") is a cell that has a value from a list of months (Jan, Feb, Mar, etc.), and you've got corresponding named ranges Ref_Jan, Ref_Feb, Ref_Mar, etc., you could just do this:
Sub Button8_Click()
Sheets("DB - Ref Current").Range("Ref_Current").Copy
Sheets("DB - Ref Monthly").Range("Ref_" & Range("MonthSelector").Value).PasteSpecial xlPasteAll
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
Basically its quite a simple thing (I think) but I can't seem to get it!
Essentially I am building a tracker and I need a date stamp put in whenever a cell is modified. I can put in the code so when anything in column b is modified to put a date in column C, but then I can't make it repeat for data put in column D to input a date in Column E.
Basically I would want a date stamp in every other Column. If it is easier to be every other row that would be fine as well I'll just change the titles around.
If its rows it would have to start from data in put in row 2 (headers), if its column data put in from column B (headers again).
Can anyone help? I've had a look online but can't seem to find the answer...
Check this event-based macro:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column Mod 2 = 0 Then
Application.EnableEvents = False
Target.Offset(0,1) = Date
Application.EnableEvents = True
End If
End Sub
Use the Worksheet_Change-Event (another good example for specific cells here).
Depending on your needs you do something like this:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Cells(1, Target.Column + 1).Value = Format(Now(), "dd.mm.yyyy")
Application.EnableEvents = True
End Sub
Its important to set .EnableEvents = False before inserting any values, otherwise it will fire the event again.
I'm making this more challenging in my head than it has to be, but since I haven't been using vba or excel recently I'm using this as my excuse. Please don't question the methodology :) as this is only a small step I'm trying eliminate for someone to save some time, until I can redo the entire process. I would do the reverse, but this is an invoice of sorts that they are using....
I'm thinking macro or function is what is needed and not a formula since the data on worksheet 2 will change each month and there is no date I can reference.
What I'd like to do:
I have a cell on worksheet 2 that will change once a month. I want to place the value of the cell from Worksheet 2 into a cell in worksheet 1 each month that she changes it.
Each month would be represented in column A and the value of the cell from Worksheet 2 during that month needs to be place in column B.
Column A Column B
12/5/2012 $3,459,877.81
1/8/2013 $9,360,785.62
2/8/2013
3/8/2013
4/8/2013
So when she changes worksheet 1 for February the number will populate next to 2/8 and so on. I was thinking do it when she saves the document, or make it a shortcut she can hit or just scrap it and tell her it's not worth.
Giving a Cell a name to reference from you can do some neat stuff with the Target parameter passed to the Worksheet_Change function:
'Add this function to the sheet that has the cell being
'+changed by the user (Sheet 2)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim strCellName As String
strCellName = "ChangeMe"
'If the cell we changed was the ChangeMeCell
If Target.Address = Sheet2.Range(strCellName).Address Then
'Store value
Dim intLastRow, intValue As Integer
intValue = Range(strCellName).Value
'Find the cell in Sheet 1 Column A that matches this month
intLastRow = Sheet1.Range("A:A").End(xlDown).Row
For Each cl In Sheet1.Range("A1:A" & intLastRow).Cells
'Ensure cell value is date
If IsDate(cl.Value) Then
'If date is today's date
'Note that Math.Round(<date>, 0 ) essentially removes the time
'+from any date value so #01/02/03 04:05:06# becomes #01/02/03#
If Math.Round(cl.Value,0) = Math.Round(Now,0) Then
'Update column B's value
Sheet1.Range("B" & cl.Row).Value = intValue
End If
End If
Next
End If
End Sub
This assumes you have the sheet layout with the "invoice values" in Sheet1 and the cell being changed in Sheet2. You need to give that cell a name.
Using the cell Name box to the left of the Function bar call the cell that changes "ChangeMe" or anything you wish to change it to, update that cell name in the first line of the function and this function will do all the rest.
It is important to note that the dates must be correctly formatted for your systems region. to make sure it is showing the right month - format them into LongDate so you can see them as 08 March 2013 instead of 03/08/13 which may get confusing the longer it goes on. Speaking as a British programmer, dates are the bane of my life!
Edit: I have update the code to compare the dates by the full date minus the time, instead of the previous monthly comparison, if you still need to subtract or add a month to either date value, just use the DateAdd("m", <date>, <value>) to add or subtract the month.
Edit: DatePart Function page is a useful resource for those wanting to know more about DatePart()
For my example, I'm using cell G4 as the one that will be updated by your coworker. You have to have some way to persist the original value of G4 in order to tell when it's been changed. The easy way to do this is to pick some cell that is out of sight of the user and store the number there so you can reference it later. Here I've chosen cell AA1. The following code must be added specifically to Sheet2 since it needs to monitor the changed events on that sheet only so it can fire when G4 is updated.
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("G4") <> Range("AA1") Then
Dim lastRow As Long
Range("AA1") = Range("G4")
lastRow = Worksheets("Sheet1").UsedRange.Rows.Count
Worksheets("Sheet1").Cells(lastRow + 1, 1).Value = Date
Worksheets("Sheet1").Cells(lastRow + 1, 2).Value = Range("AA1")
End If
End Sub
Keep in mind that this is a very "quick and dirty" approach for this task, as there are no error handlers or much flexibility in the way it works.
EDIT --
One other method you could use is referenced here, and can simply check to see if a given cell has changed, without verifying the difference in value.
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Range("G4"), Range(Target.Address)) Is Nothing Then
Dim lastRow As Long
Range("AA1") = Range("G4")
lastRow = Worksheets("Sheet1").UsedRange.Rows.Count
Worksheets("Sheet1").Cells(lastRow + 1, 1).Value = Date
Worksheets("Sheet1").Cells(lastRow + 1, 2).Value = Range("AA1")
End If
End Sub
Now, I'm able to capture the value from a formula in the cell and place it in a different cell in another worksheet. Here's my final product:
Private Sub Worksheet_Calculate()
Dim strCellName As String
strCellName = "ChangeMe"
If Sheets("Application of Moneys").Range(strCellName).Address <> PrevVal Then
Dim intLastRow, intValue As Long
intValue = Range(strCellName).Value
'Find the cell in Sheet 1 Column A that matches this month
intLastRow = Sheets("Certificate 1").Range("B:B").End(xlDown).Row
For Each cl In Sheets("Certificate 1").Range("B13:B25" & intLastRow).Cells
'Ensure cell value is date
If IsDate(cl.Value) Then
'If date is today's date
'Note that Math.Round(<date>, 0 ) essentially removes the time
'+from any date value so #01/02/03 04:05:06# becomes #01/02/03#
If DatePart("m", cl.Value) = DatePart("m", Now()) Then
'Update column B's value
Sheets("Certificate 1").Range("H" & cl.Row).Value = intValue
End If
End If
Next
End If
End Sub
I have a pivot table in an Excel worksheet that contains the result of a query made to my database. I would like to format the information automatically based on every other data set.
The information contains 4 weeks' (1 month) worth of records for each employee sorted by an employee ID number. I would like to write a module so that it will highlight every other record (employee data set) with a different color. Is this even possible to do? Thanks for the help!
If you insist with solving your problem utilizing VBA here is an example. You'll need to specify start ranges. Please not that marking whole row will use more memory (increasing file size) so I would rather use example: range("A2:E2).select ....
Sub FormatEverySecondRow()
range("A2").EntireRow.Select
Do While ActiveCell.value <> ""
Selection.Interior.ColorIndex = 15
ActiveCell.offset(2, 0).EntireRow.Select
Loop
End Sub
use a helper column (K if I count the columns in your example)
insert into K2:
=IF(ISBlank(C2),K1,MOD(K1+1,2))
then use conditional formatting to highlight the row:
Note the formula does not have a $ sign before the 2 (i.e. $K2, not $K$2)
This might be useful to you:
Sub HighlightDifferentRows()
Dim wksht As Worksheet
Dim wkb As Workbook
Dim row As Range
Dim FloatColor As Long
FloatColor = RGB(100, 100, 100)
Set wbk = ThisWorkbook
Application.ScreenUpdating = False
For Each row In Sheets(1).UsedRange.Rows
row.Interior.Color = FloatColor
If row.Cells(1, 4).Value <> row.Cells(2, 4).Value Then
FloatColor = -FloatColor
End If
Next row
Application.ScreenUpdating = True
End Sub
It alternates row colors whenever a cell value is not the same as the one below it. Right now it is set to grayish colors but you could change it to something brighter if you wanted. You could put in your own logic to get whatever colors you wanted. Good Luck.
I don't really know if this is a programming question, but I am sure one of you can easily help me with this one.
I am trying to create a automatic "inserted date" function inside excel. i.e. When a person inputs data in a row in my excel document I want another cell to automatically show the date of insertion.
Standing inside the cell i am trying to show the date, I've written the following:
=IF(ISBLANK(C20);1;TODAY())
This works great, until I open it the day after. Clearly it will set the date to "TODAY", but if I want it to only update once, at the time of the insertion - how would I do that?
Thinking something like this (Java - pseudo).
IF(!OTHER.CELL.ISBLANK() && THIS.CELL.ISBLANK()){
THIS.CELL = TODAY();
}
Now, how to do that in Excel?
Thanks in advance.
You would use the Worksheet_Change Event
Right click your sheet tab
View - Code
Copy and Paste in the code below
This code
tracks and change made to column C of the Activesheet
puts in the current data and user logon name to each corresponding cell in column D
Only changed column C cells are captured as specified in this line
Set rng1 = Intersect(Range("C:C"), Target)
The Application.EnableEvents = False is used to stop the code refiring when column D is writing to
You could easily adapt this to
1) write to a different (perhaps hidden) log sheet
2) write to a text file instead
Pls let me know if you want any updates
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng1 As Range
Set rng1 = Intersect(Range("C:C"), Target)
If rng1 Is Nothing Then Exit Sub
Application.EnableEvents = False
rng1.Offset(0, 1).Value = Now() & " - " & Environ("username")
Application.EnableEvents = True
End Sub