How to add Date every day to my first blank row - excel

I would like every day, when I open excel, that my excel would add a today's date to it. I have this code, but it isn't working, sometimes it does what it's supposed to and sometimes it skips a line, any help please?
Sub Stretching()
'This procedure will run each time you open the workbook
'Specify the required worksheet name in double quotes
Dim ws As Worksheet
Set ws = Sheets("Stretching")
'Get the last row number filled with a value in Column A
Dim lastRow As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
'Check if the last entered date is the same as the current date, if so, exit
'You need this check to see if you close the workbook then open it on the same day
'so that the code does not enter the same date again in a new row.
If ws.Cells(lastRow, 1).Value = Date Then Exit Sub
'Fill a new row in Column A with the current date
If IsEmpty(Cells(lastRow, 1)) Then
ws.Cells(lastRow, 1).Value = Date
Else
ws.Cells(lastRow, 1).Offset(1, 0).Value = Date
End If
End Sub

Some suggestions on your code:
Fully qualifying the ranges help you avoiding inconsistent results. This means, you can be running the procedure when an active sheet is different than the one you are targeting, and this line: Cells(Rows.Count, 1).End(xlUp).Row would return a different "last row" than the one you'd expect
Also try to use variable names that are easily understandable. For example, ws vs targetSheet
Please try this code and let me know if it works:
Public Sub Stretching()
'This procedure will run each time you open the workbook
'Specify the required worksheet name in double quotes
Dim targetSheet As Worksheet
Set targetSheet = ThisWorkbook.Sheets("Stretching")
'Get the last row number filled with a value in Column A
Dim lastRow As Long
lastRow = targetSheet.Cells(targetSheet.Rows.Count, 1).End(xlUp).Row
'Check if the last entered date is the same as the current date, if so, exit
'You need this check to see if you close the workbook then open it on the same day
'so that the code does not enter the same date again in a new row.
If targetSheet.Cells(lastRow, 1).Value = Date Then Exit Sub
'Fill a new row in Column A with the current date
If IsEmpty(targetSheet.Cells(lastRow, 1)) Then
targetSheet.Cells(lastRow, 1).Value = Date
Else
targetSheet.Cells(lastRow, 1).Offset(1, 0).Value = Date
End If
End Sub

Related

Keep results of last run of the day only

My goal is to make a script that every time I press the button refreshes my investment value and then posts the date and the investment value on another sheet.
I managed the following code.
Sub Refresh()
ActiveWorkbook.RefreshAll
ActiveSheet.Range("A1").End(xlDown).Offset(1, 0).Value = Date
Worksheets("Portfolio").Range("B3").Copy
ActiveSheet.Range("B1").End(xlDown).Offset(1, 0).PasteSpecial Paste:=xlPasteValues
End Sub
If I hit the button more than once, I just want to keep the last entry of the day.
My idea was to solve it with an if else, but it ignores the if:
Sub Refresh()
ActiveWorkbook.RefreshAll
If ActiveSheet.Range("A1").End(xlDown).Offset(1, 0).Value = ActiveSheet.Range("A1").End(xlDown).Value Then
Worksheets("Portfolio").Range("B3").Copy
ActiveSheet.Range("B1").End(xlDown).PasteSpecial Paste:=xlPasteValues
Else
ActiveSheet.Range("A1").End(xlDown).Offset(1, 0).Value = Date
Worksheets("Portfolio").Range("B3").Copy
ActiveSheet.Range("B1").End(xlDown).Offset(1, 0).PasteSpecial Paste:=xlPasteValues
End If
End Sub
Update Worksheet
If you don't have a button or another control to run Refresh on the ActiveSheet, I would strongly suggest you define it like Protfolio is defined.
If the code is in the ActiveWorkbook, you should definitely use
ThisWorkbook instead, which refers to the workbook containing this
code.
The Code
Option Explicit
Sub Refresh()
' Define workbook ('wb').
Dim wb As Workbook
Set wb = ActiveWorkbook
' Do.
wb.RefreshAll
' Define Target Worksheet ('tgt').
Dim tgt As Worksheet
Set tgt = wb.ActiveSheet
' Define Old Date Cell ('cel').
Dim cel As Range
Set cel = tgt.Range("A1").End(xlDown)
' Check if Old Date Cell does not contain today's date.
If cel.Value <> Date Then
' Does not contain today's date:
' Define New Date Cell ('cel'), the cell below Old Date Cell.
Set cel = cel.Offset(1, 0)
' Write today's date to New Date Cell.
cel.Value = Date
Else
' Does contain today's date:
' Do nothing because Old Date Cell is becoming New Date Cell.
End If
' Define Source Worksheet ('src').
Dim src As Worksheet
Set src = wb.Worksheets("Portfolio")
' Write value from Source Cell to Target Cell.
' (Source Cell is next to New Date Cell).
cel.Offset(0, 1).Value = src.Range("B3").Value
End Sub

How to Delete rows according to criteria in cells

I am trying to automate some date filtering for work.
I want to delete rows if they do not fall under this time stamp
2:00am - 10:00am
So if the time is before 2:00am or after 10:00am delete the entire row.
There are multiple rows like this.
I am not sure where to even start because I am very beginner and need an easy code to follow.
Here is what the data would look like
This is similar to this question here where I gave a similar answer. You can give this a try, though this assumes your times are in the 24 hour format and assumes you only want to delete that specific cell and not the entire row.
Sub TimeDelete()
'Declare your variables
Dim timeRng As Range, early As Long, late As Long, lrow As Long
'Finds the last row with a time in it in Column F
lrow = ThisWorkbook.Worksheets("Sheet1").Cells(Rows.Count, 6).End(xlUp).Row
'Define the times you want to compare against
early = "02:00:00"
late = "10:00:00"
'Specifies the range the times are in
Set timeRng = ThisWorkbook.Worksheets("Sheet1").Range(Cells(1,6), Cells(lrow,6))
'Use a For loop to check each value in the range
For Each Cell In timeRng.Cells
If TimeValue(Cell.Value) >= TimeValue(early) And TimeValue(Cell.Value) <= TimeValue(late) Then
Cell.Delete Shift:=xlToLeft 'Deletes cell if it meets the criteria and shifts remaining cells in the row to the left.
End If
Next Cell
End Sub
My VBA is a bit rusty, but this should work
Sub DelStuff()
Dim WB As Workbook
Dim Sheet As Worksheet
Set WB = ActiveWorkbook
Set Sheet = WB.ActiveSheet
For Each r In Sheet.UsedRange.Rows
If Cells(r.Row, "F").Value <= Date & " " & #2:00:00 AM# Or Cells(r.Row, "F").Value >= Date & " " & #10:00:00 AM# Then
r.EntireRow.Delete
End If
Next r
End Sub

Repeating a Macro in Excel untill it reaches a blank cell

I am very new to VBA in excel and I have recorded and modified a macro that gets a value then based on an "IF" statement it uses the answer to calculate a value in a certain cell . I need to repeat this until there is a blank cell in column A.
My Data is
Part Number reported actual waste in the first 4 columns here follows my code that I need to repeat until column A is blank.
Sub MissingMix()
'
' MissingMix Macro
' Calculates Missing Mix based on scrap
'
' Keyboard Shortcut: Ctrl+q
Application.Goto Reference:="R1C1"
Application.Goto Reference:="R3C8"
ActiveCell.FormulaR1C1 = "=IF(RC[-5]-RC[-6]>0,SUM(RC[-5]-RC[-6])*RC[+1],"""")"
Application.Goto Reference:="R3C9"
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-8],'QAD Weights'!RC[-8]:R[37]C[-5],4)"
End Sub
use this:
' get active sheet
Dim CurrentSheet As Worksheet
Set CurrentSheet = ActiveWorkbook.ActiveSheet
' defining starting row
Dim Values As Range
Set Values = Rows(5)
For i = 2 To Values.Cells.Count - 1
If Values.Cells(i).Text <> "" Then
' Do Something ...
End If
Next
you can also do the check with If Not IsEmpty(Cells(i).Value) Then ...
EDIT
There is another way that you can handle this.
Dim CurrentSheet As Worksheet
Set CurrentSheet = ActiveWorkbook.ActiveSheet
' getting the lastrow by jumping to the last filled row of cell(1,1)
' cell(1,1) means the cell at row=1 and column=1 (column "A")
Dim LastRow As Long
LastRow = CurrentSheet.Cells(1, 1).End(xlDown).Row
MsgBox LastRow

VBA check entire range has valid date and is not blank?

I have a workbook like so:
Dates
01/02/2017
01/03/2017
BLANK
01/02/2017
I am trying to run a macro but only if all cells in my range are valid dates and not empty.
I am using the below:
Dim cell As Range
'With my workbook, lets check the data
With wb.Worksheets(1)
Lastrow = .Cells(.Rows.count, "G").End(xlUp).Row
'Data Check: Are all dates valid?
For Each cell In Range("E9:E" & Lastrow)
If IsDate(cell.Value) And Not IsEmpty(cell.Value) Then
Continue
Else
Exit Sub
End If
Next
End With
But this is not working. The macro still runs no matter what! If it matters my cells in this column Are data validation lists.
Please can someone show me where i am going wrong?
Reverse the logic a bit:
Dim cell As Range
'With my workbook, lets check the data
With wb.Worksheets(1)
Lastrow = .Cells(.Rows.Count, "G").End(xlUp).Row
'Data Check: Are all dates valid?
For Each cell In Range("E9:E" & Lastrow)
If Not IsDate(cell.Value) Or Trim(cell.Value) = "" Then
Exit Sub
End If
Next
' the rest of your code.
' it will not get here if there are any blanks in or non dates in the range.
End With

Find text in column A e.g. ID number "10502"

I currently have a list of employees which have completed training within the whole company. I am trying to create a macro to find the employees with my department via their employee number and copy them over to Worksheet 2.
Employee Number is in column A. This employee may have multiple entries under their ID. I want to copy all information on that row from Column A to Column N. I than want to paste those entries into Sheet2.
We have 187 Employees within our department. Any help with finishing this would be greatly appreciated.
Sub ()
Worksheets("Sheet1").Activate
Range("A1").Activate
' Find the first ID Number
Cells.Find(What:="10503", After:=ActiveCell, SearchDirection:=xlPrevious).Select
' copy and paste Text2
ActiveCell.Offset(0, 0).Copy
Worksheets("Sheet2").Select
Range("A65000").End(xlUp).Offset(1, 0).Select
ActiveCell.PasteSpecial (xlPasteAll)
Worksheets("Sheet1").Activate
End Sub
Try this:
Sub FindandCopyRow()
Dim targetSh As Worksheet
Set targetSh = ThisWorkbook.Worksheets("Sheet2")
Dim i As Long
For i = 1 To Cells(Rows.Count, "A").End(xlUp).Row
If Cells(i, 1).Value = "10503" Then '--->change ID here as required
Rows(i).EntireRow.Copy Destination:=targetSh.Range("A" & targetSh.Cells(Rows.Count, "A").End(xlUp).Row + 1)
End If
Next i
End Sub
I just added some data to #Mrig's answer.
One being the use of Application.InputBox which prompts the user to insert the employee number instead of the user editing the code every time.
I also just Sheet referencing for the various part of the For loop, always good to reference the sheets you are in to avoid consufion for the next user and then Application itself.
Sub FindandCopyRow()
Dim DataSh As Worksheet
Set DataSh = ThisWorkbook.Worksheets("Sheet1")
Dim targetSh As Worksheet
Set targetSh = ThisWorkbook.Worksheets("Sheet2")
Dim EmployeeNumber As Long
'This allows you to enter an employee number and not have to edit the code every time
EmployeeNumber = Application.InputBox(Prompt:="Please Enter Employee Number:", Type:=1)
'Try use descriptive naming for variables.....always
Dim DataShRowRef As Long
'Remember to always reference the sheet you are in when counting and copying etc
For DataShRowRef = 1 To DataSh.Cells(DataSh.Rows.Count, "A").End(xlUp).Row
If DataSh.Cells(DataShRowRef, 1).Value = EmployeeNumber Then
DataSh.Rows(DataShRowRef).EntireRow.Copy Destination:=targetSh.Range("A" & targetSh.Cells(targetSh.Rows.Count, "A").End(xlUp).Row + 1)
End If
Next DataShRowRef
End Sub

Resources