I have a little problem with my VBA code. I use the code below to display every date in a date range. So if the date range is 3 Dec - 5 Dec, it will display 3 Dec in cell E10, 4 Dec in cell E11 and 5 Dec in cell E12. This works fine, however I need to add 4 blank cells below every date (so 3 Dec will be in cell E10, but the 4th of December will be shown in cell E15 etc).
Private Sub cmdOK_Click()
Dim RowCount As Long
Dim ctl As Control
' Check user input
If Me.SdPicker.Value = "" Then
MsgBox "Please enter an start date.", vbExclamation, "Start data error"
Me.SdPicker.SetFocus
Exit Sub
End If
If Me.EdPicker.Value = "" Then
MsgBox "Please enter the end date.", vbExclamation, "End date error"
Me.EdPicker.SetFocus
Exit Sub
End If
' Write data to worksheet
With Worksheets("Projection_Daily").Range("X1")
.Value = Me.SdPicker.Value
End With
With Worksheets("Projection_Daily").Range("Y1")
.Value = Me.EdPicker.Value
End With
' Close the form to open Output sheet and implement date range
Worksheets("Projection_Daily").Activate
Worksheets("Projection_Daily").Columns(5).ClearContents
Dim StartDate As Date
Dim EndDate As Date
Dim NoDays As Integer
StartDate = Worksheets("Projection_Daily").Range("X1").Value
EndDate = Worksheets("Projection_Daily").Range("Y1").Value
NoDays = EndDate - StartDate + 4
Worksheets("Projection_Daily").Range("E10").Value = StartDate
Worksheets("Projection_Daily").Range("E10").Resize(NoDays).DataSeries Rowcol:=xlColumns, Type:=xlChronological, Date:=xlDay, Step:=1, Stop:=EndDate, Trend:=False
Unload Me
End Sub
This is the code I currently use, I have tried to insert .Offset(4,0) to the code but with no luck. I hope you can help me with this.
Thanks!
Try using a Loop condition like this:
i = 1 'To loop through the no of days
j = 10 'To start from row no 10
For i = 1 To NoDays 'Nodays = Enddate-Startdate
Sheet1.Cells(j, 5).value = StartDate
StartDate = StartDate + 1
j = j + 5 'To add a gap of 4 blank rows
Next i
Related
I am trying to create this loop inside the loop so as to print inside the cells in the below range -> Week i where i is from 1 to 6 and it raises by one each time we move to a cell down...
So, in this case, for D2 I want Week 1, For D3 Week 2 etc.. Any ideas? I appreciate your time!
Sub INPUT()
Sheets("1").Select
For Each cell In range("D2:D7")
For i = 1 To 6
cell.Value = "Week +" & i
i = i + 1
Next i
Next cell
End Sub
You only need the one loop:
Sub INPT()
With Sheets("1")
i = 1
For Each cell In .Range("D2:D7")
cell.Value = "Week +" & i
i = i + 1
Next cell
End With
End Sub
I am looking for a way to remove rows based on the termination date of an employee. I don't want blank cells to be deleted because those employees are still active. I have a text box that pops up and asks for the dates and then show the entered date. Then it is supposed to search column G for any dates prior to the entered date and delete those rows, skipping any row that is blank.
I have been searching everywhere for a way to do this but I can't get the Macro to stop deleting every row but the headers. The dates are in column G and it's about 46 rows but that can change.
Sub DateSelectandClean()
'
' DateSelectandClean Macro
' User enters date and spreadsheet deletes everything prior to that date, ignoring empty cells.
Application.ScreenUpdating = False
Dim W2Year As Date, N As Long
Dim dt As Date
W2Year = CDate(Application.InputBox(Prompt:="Please enter W2 Year as xx/xx/xxxx Date:", Type:=2))
MsgBox W2Year
N = Cells(Rows.Count, "G").End(xlUp).Row
For i = N To 2 Step -1
dt = Cells(i, 1).Value
If (Cells(i, 1).Value <> "" And dt < W2Year) Then
Cells(i, 1).EntireRow.Delete
End If
Next i
Application.ScreenUpdating = True
End Sub
Sample Data
The main issue is you're checking the "A" column for your date info, and deleting based on that. If your dates are in "G", you should check Cells(x,7), not Cells(x,1).
Sub DateSelectandClean()
'
' DateSelectandClean Macro
' User enters date and spreadsheet deletes everything prior to that date, ignoring empty cells.
Application.ScreenUpdating = False
Dim W2Year As Date, lastRow As Long, i As Long, dateCol As Long
Dim dt As Date
dateCol = 7 ' for column G
Do While W2Year = "00:00:00"
W2Year = Format(Application.InputBox(Prompt:="Please enter W2 Year as xx/xx/xxxx Date:", Type:=2), "mm/dd/yyyy")
MsgBox W2Year
Loop
lastRow = Cells(Rows.Count, dateCol).End(xlUp).Row
For i = lastRow To 2 Step -1
'If Cells(i, dateCol).Value <> "" Then
If IsDate(Cells(i,dateCol)) Then
dt = CDate(Format(Cells(i, dateCol).Value, "mm/dd/yyyy"))
If dt <= W2Year Then
Cells(i, dateCol).EntireRow.Delete
End If
End If
Next i
Application.ScreenUpdating = True
End Sub
I also change the variables from Date to String which allows a little bit of error catching when the user inputs info. You can edit that back if you wish, I was just thinking of a time when someone puts in "wrong" or incorrectly formatted info.
Your code might be getting an issue in blank date.
I separate the IF so that it won't continue the validation on date.
e.g. IF "" < #01/01/2017#
Try this, not much changes though:
Sub DateSelectandClean()
' DateSelectandClean Macro
' User enters date and spreadsheet deletes everything prior to that date, ignoring empty cells.
Application.ScreenUpdating = False
Dim dateCol, iRow
Dim W2Year As Date, N As Long
Dim dt As String
W2Year = CDate(Application.InputBox(Prompt:="Please enter W2 Year as dd/mm/yyyy Date:", Type:=2))
MsgBox W2Year
N = Cells(Rows.Count, "G").End(xlUp).Row
dateCol = 7
For iRow = N To 2 Step -1
dt = Cells(iRow, dateCol).Value
If (Cells(iRow, dateCol).Value <> "") Then
If (CDate(dt) < CDate(W2Year)) Then
Cells(iRow, dateCol).EntireRow.Delete
End If
End If
Next
Application.ScreenUpdating = True
End Sub
I am trying to perform the following sequence of actions:
Open an input box where a start date would be entered, and put that date in a specified cell on a specified sheet.
Open an input box where an end date would be entered, and put that date in a specified cell on a specified sheet.
Select rows of data from a large dataset that falls between and/or on these dates.
Copy that data to another sheet (sheet2).
Sample data:
Sol Id Acct No Name DATE
20 12 JOHN STEVE 16/09/2009
20 13 ROBERT V 31/07/2011
4 14 JOHNNY WALKER 30/04/2012
20 15 LA PRUDENCEE 30/04/2013
20 16 ddd 30/06/2013
11 17 DD 16/09/2013
20 18 EED 30/09/2013
5 19 EED 01/10/2013
20 20 DD 30/11/2013
2 21 RRR 19/12/2013
7 22 RDS 01/01/2014
20 23 DSS 24/01/2014
5 24 223 31/01/2014
5 25 44 31/01/2014
20 26 555 31/01/2014
20 27 666 24/02/2014
The dates continue till 31/12/2016. I want to select the start date 16/09/2009, end date 31/12/2015, and paste in sheet2.
My VBA code is:
Option Explicit
Sub Data_Date_Filter()
Dim sDate As Variant, eDate As Variant
sDate = Application.InputBox("Enter the starting date as mm/dd/yyyy", Type:=1 + 2)
eDate = Application.InputBox("Enter the Ending date as mm/dd/yyyy", Type:=1 + 2)
Application.ScreenUpdating = False
Sheet2.Cells.ClearContents
With Sheet1
.AutoFilterMode = False
.Range("D1").CurrentRegion.AutoFilter field:=2, Criteria1:=">=" & sDate, Operator:=xlAnd, Criteria2:="<=" & eDate
.Range("D1").CurrentRegion.SpecialCells(xlCellTypeVisible).Copy Sheet2.Range("A1")
End With
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
It does not copy to sheet 2.
The code below will do what I believe you're trying to do. Basically you were missing the code to actually paste the values into Sheet2 from Sheet1.
I did the following:
Added error checking to the date variables since clicking "Cancel" from the input box returned a False value; this caused the autofilter to error.
Created wkb and wks variables to make the workbook and worksheet methos easier to follow.
Added wkb.Worksheets("Sheet2").Range("A1").PasteSpecial to handler pasting the copied values into sheet 2.
Reformatted method properities to follow VBA standards and not the skrewy Excel (":=") syntax.
Option Explicit
Sub Data_Date_Filter()
On Error GoTo ErrHandler
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Dim sDate As Variant
Dim eDate As Variant
Set wkb = Application.ThisWorkbook
sDate = Application.InputBox("Enter the starting date as mm/dd/yyyy", , , , , , , vbOKCancel)
eDate = Application.InputBox("Enter the Ending date as mm/dd/yyyy", , , , , , , vbOKCancel)
'CHECK IF DATES ARE NULL DUE TO CANCEL BUTTON CLICK
If sDate = False Or eDate = False Then Exit Sub
'TURN OFF SCREEN UPDATING AND COPY/PASTE VALUES FROM SHEET1 TO SHEET2
Application.ScreenUpdating = False
wkb.Worksheets("Sheet2").Cells.ClearContents
Set wks = wkb.Worksheets("Sheet1"): wks.Activate
With wks
.Range("A1:D1").AutoFilter
.Range("D1").AutoFilter 4, ">=" & sDate, xlAnd, "<=" & eDate
.Range("D1").CurrentRegion.SpecialCells(xlCellTypeVisible).Copy
End With
wkb.Worksheets("Sheet2").Range("A1").PasteSpecial
With Application
.CutCopyMode = False
.ScreenUpdating = False
End With
Set wks = Nothing: Set wkb = Nothing
ExitHandler:
Exit Sub
ErrHandler:
Stop: Debug.Print Err.Description: Err.Clear: Resume
End Sub
Hope this helps!
My requirement is:
I want to enter date from 1st Jan to 31st Jan in columns E5 to AI5. Currently using the below code which is not working.
Secondly year i m taking as user input which should change every time.
Sub LoopA()
Call Using_InputBox_Method
Dim i As Integer
Dim j As Integer
Dim PH As Integer
i = 5
For j = 5 To 35
Cells(i, j).Value = "=Date(E1,1,j)"
Next j
End Sub
Public Function Using_InputBox_Method() As Integer
Dim Response As Integer
' Run the Input Box.
Response = Application.InputBox("Enter a Year.", _
"Number Entry", , 250, 75, "", , 1)
' Check to see if Cancel was pressed.
If Response <> False Then
' If not, write the number to the first cell in the first sheet.
Worksheets(1).Range("E1").Value = Response
End If
Using_InputBox_Method = Response
End Function
A)
Anything within " will be considered as a String. So "=Date(E1,1,j)" is just a string. What you want, I guess is
"=Date(E1,1," & j & ")"
B)
For j = 5 To 35
Are you sure you want to go up till 35? The max you can have in any month is 31 :)
Syntax of =Date() is DATE(year,month,day)
Also you would need an additional check here to see if it is a valid date. For example 30th Feb will give you an error.
C)
InputBox should be avoided to accept dates. It can generate errors. You may want to use THIS. If you still want to use InputBox then you will have to do validations to ensure that there are no errors.
D)
Regarding, the Year changing automatically, You will have to increment the Year in Column E once the user automatically enters the date.
Is this what you are trying?
Sub Sample()
Dim Yr As Long, i As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Yr = Application.InputBox("Enter a Year.", _
"Number Entry", , 250, 75, "", , 1)
'~~> Set it to whatever Year Range you want
If Yr < 1900 Or Yr > 9999 Then
MsgBox "Incorrect Year"
Exit Sub
End If
With ws
.Range("E1").Value = Yr
For i = 5 To 35
.Cells(5, i).Formula = "=Date(E1,1," & (i - 4) & ")"
Next i
End With
End Sub
I am calculating the number of work hours (8am to 8pm) between the 2 given dates, excluding Weekends and Public holidays, but my code syntax is incorrect.
Sample data:
Start day: 17/06/2011 08:00:00 AM
End day: 19/06/2011 08:00:00 PM
Sub SLA_Days_Resolved_F()
Dim x As Integer
' Set numrows = number of rows of data.
NumRows = Range("F2", Range("F2").End(xlDown)).Rows.Count
Dim total As Integer 'to count the total hours
Dim st As String 'start date cell
Dim en As String 'end date cell
Dim destCell As String
Dim d As Date ' for the loop
total = 0
' Establish "For" loop to loop "numrows" number of times.
For x = 2 To NumRows + 1
st = "G" & CStr(x) 'reference to the cells
en = "D" & CStr(x)
'loop from start date to end date
For d = Date(Range(st)) To Date(Range(en))
'check if the current date is found is a Public holiday in the range or if a weekend
If ((Vlookup(d,lookups!$o$3:$p$26,2,false))=1) or (weekend(d))Then
'minus 8 to remove hours before 8am.
total = (total + Hour(d) + minutes(d) / 60) - 8
End If
Next
Next
End Sub
You are not assigning any values to variables st or en.
Date is not a function available in VBA. You will probably need to use DateSerial function. Here is a simple example of looping over dates which you should be able to modify.
Sub LoopDates()
Dim d As Date
'Loop the days beteween today and March 1, 2013.
For d = DateSerial(Year(Now), Month(Now), Day(Now)) To DateSerial(2013, 3, 1)
Debug.Print d 'Prints the "d" value in the immediate window.
Next
End Sub
Also, you can't just put worksheet formulae in VBA. This line is definitely wrong syntax for Vlookup, and Weekend is not a formula that I'm aware of (testing it seems to confirm it is not a valid call on worksheet or in VBA.
If ((Vlookup(d,lookups!$o$3:$p$26,2,false))=1) or (weekend(d))Then
Rewrite as:
If Application.WorksheetFunction.Vlookup(d,Sheets("lookups").Range("$o$3:$p$26"),2,false)=1 _
or Not Application.WorksheetFunction.Weekday(d) Then
ANOTHER EXAMPLE of a date loop where I have dimensioned the variables in what I believe to be a more efficient manner:
Sub Test()
Dim st As Range
Dim x As Integer
Dim stDate As Date
Dim enDate As Date
Dim d As Date
Dim numRows as Long
NumRows = Range("F2", Range("F2").End(xlDown)).Rows.Count
For x = 0 To NumRows-2
'SET YOUR VARIABLES HERE
' This may seem redundant or unnecessary for this case, but it makes structuring nested
' loops easier to work with, and then there are fewer places to make changes,
' if you need to make changes.
Set st = Range("G2").Offset(x, 0)
Set en = Range("D2").Offset(x, 0)
stDate = DateSerial(Year(st), Month(st), Day(st))
enDate = DateSerial(Year(en), Month(en), Day(en))
'Then, loop through the dates as necessary
For d = stDate To enDate
Debug.Print d
'Do your code here.
Next
Next
End Sub