Autofill to a specific date - vba

I am working with date data and want to autofill to a specific date. The specific date will be stored as value X. X is the last value in column A
I've looked at some other posts here on StackOverflow, but the issue I keep running into is setting my final "value". My final value will not be a number, but a date to stop at.
With ThisWorkbook.Sheets("Form Date 2")
'Select this workbook
Dim X as Date
'I am not sure what I need to Dim this as
Range("B2").Value = Range("A2").Value
'B2 is the value I want to autofill down with
X = Range("A" & Rows.Count).End(xlUp).Value
'X will be the last value in column A
Range("B2").Autofill Destination:=Range("B2:B" & X), Type:=xlFillSeries
'Not sure what to set my Type as
End With
So the final result would be, Column B would obtain all dates from A1 to last value in A (02/04/2018-05/06/2018). Format should be dd/mm/yyyy.
In Column A I have a whole bunch of dates, but some are missing, so I am grabbing all the missing ones as well.
With the picture below I have the Dates column. I want VBA to spit out the All Dates column. So The code will copy and paste A2 over to B2 and then autofill until the last value in column A(not row). So in this example All Dates should continue down until value/date 01/06/2018.

Perhaps this will work:
With ThisWorkbook.Sheets("Sheet2")
'Select this workbook
Dim X As Integer
'I am not sure what I need to Dim this as
.Range("B2").Value = .Range("A2").Value
'B2 is the value I want to autofill down with
X = .Range("A" & .Rows.Count).End(xlUp).Row
'X will be the last value in column A
.Range("B2").Select
Selection.AutoFill Destination:=.Range("B2:B" & X), Type:=xlFillDefault
'Not sure what to set my Type as
End With
Updated Code to fill till the date on the last cell of Column A:
With ThisWorkbook.Sheets("Sheet2")
'Select this workbook
Dim X As Integer
'I am not sure what I need to Dim this as
.Range("B2").Value = .Range("A2").Value
'B2 is the value I want to autofill down with
X = .Range("A" & .Range("A" & .Rows.Count).End(xlUp).Row).Value - .Range("B2").Value
'X will be the last value in column A
.Range("B2").Select
Selection.AutoFill Destination:=.Range("B2:B" & X + 2), Type:=xlFillDefault
'Not sure what to set my Type as
End With

This code works fine :
Sub test()
Dim X As Integer
ThisWorkbook.Sheets("Sheet2").Range("B2").Value = Range("A2").Value
'B2 is the value I want to autofill down with
X = ThisWorkbook.Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row
'X will be the last value in column A
ThisWorkbook.Sheets("Sheet2").Range("B2").AutoFill Destination:=ThisWorkbook.Sheets("Sheet2").Range("B2:B" & X), Type:=xlFillDefault
End Sub
You're welcome :)

Related

VBA code to get week number from given date

I am working with Excel 2010.
I wish to convert a given date from the format mm/dd/yyyy to the format Wyy"weeknumber"
For example, 4/10/2017 would become W1715, since it is week 15 of 2017.
The below shown image is of the excel table I am working on. I want to convert the dates in column LT Verification - Planned Date to the week number format mentioned above, in column LT Verification - Planned Week Numbers.
Edit: Because this is part of a larger VBA process, I need it to be in VBA, not a cell formula.
I have written the following code:
Public Sub WeekNumbers()
Dim lastRow As Integer
lastRow = Range("A1:AZ1").Find("*", , , , xlByRows, xlPrevious).Row
Dim myRange As Range
Set myRange = Range("A1:AZ1" & lastRow)
Dim myCell As Range
For Each myCell In myRange
myCell.Offset(0, 1).Value = "W" & Right(Year(myCell.Value), 2) & Application.WorksheetFunction.WeekNum(myCell.Value)**
Next myCell
End Sub
This code gives me error at myCell.Offset(0, 1).Value = "W" & Right(Year(myCell.Value), 2) & Application.WorksheetFunction.WeekNum(myCell.Value)
Here I have a excel workbook which will be updated every week. So, each time it is updated, it runs a macro to import data from another file & perform the week number activity & create a pivot table.
So, the sheet name changes every week. Also, the column headers may be in different columns in different weeks. Also, the number of rows may also change every week.
So, I need to specify column & row range dynamically based on that weeks data.
And have the week numbers in the column based on the column header rather than the column name (A or B or Z...)
This can be achieved easily with a cell formula:
="W" & RIGHT(YEAR(A1),2) & WEEKNUM(A1)
Where A1 can be replaced by the cell containing the date.
In VBA this is equivalent to
With Thisworkbook.Sheets("Sheet1")
.Range("A2").Value = "W" & Right(Year(.Range("A1").Value), 2) & Application.WorksheetFunction.WeekNum(.Range("A1").Value)
End With
Edit:
To fill an entire range, you could loop over the cells, apply the VBA calculation as above.
Dim myRange as Range
Set myRange = Thisworkbook.Sheets("Sheet1").Range("A1:A10")
Dim myCell as Range
For Each myCell in myRange
myCell.Offset(0,1).Value = "W" & Right(Year(myCell.Value), 2) & Application.WorksheetFunction.WeekNum(myCell.Value)
Next myCell
There are many methods for finding the last row in a range, so I'll leave that to you if you don't know your range.
Edit 2: in response to your error edit.
You have used the following line to define your range:
Set myRange = Range("A1:AZ1" & lastRow)
Let's imaging you have lastRow = 20, you now have
myRange.Address = "A1:AZ120"
Which is clearly wrong, you shouldn't have the 1 after the AZ. Also I don't know why you've gone to column AZ, if all of your date data is in column A, you should use
Set myRange = Range("A1:A" & lastRow)
The loop you've implemented uses an offset, so the values in column B are changed to reflect those in column A. You can't then set column C according to column B!
In VBA, you can get your string by using the Format function. "\Wyyww" is the format you are looking for, where \ is used to escape the interpretation of the first W character and to take it as a litteral.
myCell.Offset(0,1).Value = Format(myCell.Value, "\Wyyww")
More
You have to setup correctly the range for your loop. If your dates are in some column with header "LT Verificiation - Planned Date", you can try this:
Dim ws As Worksheet
Set ws = ActiveSheet ' <-- you can change this into something explicit like Sheets(someIndex)...
Dim myCell As Range
Set myCell = ws.Rows(1).Find("LT Verificiation - Planned Date")
For Each myCell In ws.Range(myCell.Offset(1), ws.Cells(ws.Rows.Count, myCell.Column).End(xlUp))
If IsDate(myCell.value) Then myCell.Offset(, 1).value = Format(myCell.value, "\Wyyww")
Next myCell
I don't think you need VBA for this, try this formula:
=RIGHT(YEAR(A1),2)&WEEKNUM(A1)&"W"
Of course, if you insist on VBA, you can always turn Excel Formulas into VBA code. In this case:
Dim rngInput As Range
Dim rngOutput As Range
With Application.WorksheetFunction
rngOutput.Value = .Right(.Year(rngInput.Value), 2) & .Weeknum(rngInput.Value) & "W"
End With
Or you may even set the Formula, and Insert the Value, like this
Dim rngInput As Range
Dim rngOutput As Range
rngOutput.Formula = "=RIGHT(YEAR(" & rngInput.Address(False, False) & "),2)&WEEKNUM(" & rngInput.Address(False, False) & ")&""W"""
rngOutput.Value = rngOutput.Value

how to delete cell value if cell is containing special text

I want to delete the value of a cell with vba, if the cell contains the phrase "01.01.1970 01:00:00"
The cell should be empty afterwards.
This date is only in column C and can exist in many rows.
The sheet has a lot of rows with different dates.
I only found ways, how to delete an entire row or column, if a cell contains a specific phrase, but I only want to delete the cell value.
Can someone help me?
Look at the Range.Replace method. You will want to localize the cells to be examined to column C.
with activesheet '<-set this worksheet reference properly!
.columns(3).replace what:="01.01.1970 01:00:00", _
replacement:=vbnullstring, lookat:=xlwhole
end with
Try this: (Untested)
Dim RowCount as integer, i as integer
RowCount = Range("C" & .Rows.Count).End(xlUp).Row
For i = 1 to RowCount
If Range("C" & i).Value = "01.01.1970 01:00:00" Then
Range("C" & i).ClearContents
End If
Next i
I found a solution / workaround with the following code
'START: CONVERT UNIX TIMECODE
Range("D1").EntireColumn.Insert
lastRow = Range("C" & Rows.Count).End(xlUp).Row
Range("D2").Formula = "=(C2/86400)+25569+(+1/24)"
Range("D2").AutoFill Destination:=Range("D2:D" & lastRow)
Columns("D").NumberFormat = "DD.MM.YYYY HH:MM:SS"
Columns("D").Copy
Columns("D").PasteSpecial xlPasteValues
Columns("C").Delete
Range("C1").Value = "'Druckbeginn"
'END: CONVERT UNIX TIMECODE
'START: CHANGE FORMAT OF COLUMN D TO TEXT
Columns("C").NumberFormat = "#"
'END: CHANGE FORMAT OF COLUMN D TO TEXT
'START: DELETE SPECIFIC TEXT, THE NUMBER 25569.* IS FOR THE DATE AND EACH TIME FROM 01.01.1970
Columns("C").Replace "25569.*", "", xlPart
'END: DELETE SPECIFIC TEXT
'START: CHANGE FORMAT OF COLUMN D TO DATE AND TIME
Columns("C").NumberFormat = "DD.MM.YYYY HH:MM:SS"
'END: CHANGE FORMAT OF COLUMN D TO TEXT

Matching and inserting records in excel

I have two sheets of data. One sheet has Primary Id with 4 fields and other has primary Id with 2 fields.
Sheet A Sheet B
ID Name Price Type Category ID Name Price
1 S Normal 2 Aus 500
2 N Default 1 Ind 400
Basically I need to match the ID of both sheets and copy the corresponding Name and Price in sheet A form Sheet B. I have tried the following code,
Sub Copy()
lastrowA = Worksheets("SheetA").Cells(Rows.Count, "A").End(xlUp).Row + 1
Set rngA = Range("A2" & lastrowA)
lastrowB = Worksheets("SheetB").Cells(Rows.Count, "A").End(xlUp).Row + 1
Set rngB = Range("A2" & lastrowB)
For Each x In rngB
For Each y In rngA
If x.Value() = y.Value Then
' Copy paste name and price form B to A
End If
Next
Next
End Sub
It's never a good idea to use a reserved word as the name of your macro. Particularly so if you plan to use a .Copy operation within the macro.
Sub MyCopy()
Dim lastrowA As Long
With Worksheets("SheetA")
lastrowA = .Cells(Rows.Count, "A").End(xlUp).Row
With .Range("B2:C" & lastrowA)
.Formula = "=IFERROR(VLOOKUP($A2, 'SheetB'!$A:$C, COLUMN(B:B), FALSE), """")"
.Value = .Value
End With
End With
End Sub
That bulk populates the entire region with the appropriate formula without looping then converts the returned values to raw values. Any non-matches will be blank rather than #N/A errors.
Does it have to be done without using formulas? I'm not sure if I'm missing something, but surely you can just use either a Vlookup or an Index Match?
If entering the formula from VBA:
Cells(2,2).FormulaR1C1 = "=INDEX(Sheet2!R2C2:R3C3,MATCH(RC[-1],Sheet2!RC[-1]:R[1]C[-1],0),1)"
Cells(2,3).FormulaR1C1 = "=INDEX(Sheet2!R2C2:R3C3,MATCH(RC[-2],Sheet2!R2C1:R3C1,0),2)"
Then you can find the last row in the ID column on sheet 1, and fill the formula down both of the columns. Once the formula has been filled down, just copy and paste as values.
Dim lstRow As Long
lstRow = Sheets("Sheet 1").Cells(Rows.Count, 1).End(xlUp).Row '' find last row
Range(Cells(2, 2), Cells(lstRow, 3)).FillDown
Range(Cells(2, 2), Cells(lstRow, 3)).Copy
Cells(2, 2).PasteSpecial Paste:=xlPasteValues
Edit: You can use the lstRow variable within the VBA formula to make sure the formula is covering the whole range everytime the automation is run. You can use the 'Record Macro' button within excel to get the code for a formula, if you are not comfortable creating them yourself.
The Problem with your code is that
Set rngA = Range("A2" & lastrowA)
evaluates to Range("A25") for lastRowA=5.
If you want to address multiple cells, use
Set rngA = Range("A2:A" & lastrowA)
to get Range("A2:A5") for lastRowA = 5.
Besides that, formulas as already mentioned are an elegant solution as well.

Select sheet defined as date

I do have a workbook where multiple sheets are named based on date (in format MMDDD). This macro should loop trough all date sheet (like 01OCT, 02OCT, .... 30OCT) select range and copy it into new sheet.
Selecting cells, copying them and so is not really problem, and that is working perfectly. However I do have a problem defining sheet name. I would like user in the beginning define month and number of days in month and month using InputBox.
So if user select month = "FEB" and DaysMonth = 28, I would like macro to loop trough sheets named 01FEB, 02FEB, 03FEB, .... 28FEB.
Sub Merge_whole_month()
Application.ScreenUpdating = False
Dim month As String
month = InputBox(Prompt:="Please enter month in format MMM", _
Title:="Month")
Dim DaysMonth As Long
DaysMonth = InputBox(Prompt:="Please enter number of days in month", _
Title:="Days")
'create new sheet for results
Sheets.Add.Name = "Merge"
'loop
For i = 1 To DaysMonth
i = Format(i, "##")
Sheets(i & month).Activate 'here is the problem
'select cell G3, then all "non-empty" cells to the right and down and COPY
Range(Range("G3", Range("G3").End(xlToRight)), Range("G3", Range("G3").End(xlToRight)).End(xlDown)).Select
Selection.Copy
Sheets("Merge").Activate 'activate sheet where cells needs to be copied
'find last cell in 2nd row in sheet
lastCol = Cells(2, Columns.Count).End(xlToLeft).Column
lastCol = lastCol + 1
Cells(1, lastCol) = i & month 'log date and month in cell above
Cells(2, lastCol).Select
ActiveSheet.Paste 'Paste
Next i
Application.ScreenUpdating = True
End Sub
Many thanks in advance for any help!
The problem lies in the facto that i = Format(i, "##") does not make i less than 10 appear as 01 etc. To fix this i would do this:
Dim sDate As String
sDate = CStr(i)
If Len(sDate) < 2 Then
sDate = "0" & sDate
End If
Place that code within your for-loop before Sheets(i & month).Activate and remove i = Format(i, "##").
EDIT:
It also seems that for me using Format(i, "0#") gives the string you were looking for. However you will still need to assign this to a String variable or change Sheets(i & month).Activate to Sheets(Format(i, "0#") & month).Activate.
Here is the documentation on the Format() function. I suggest reading it.

VBA: Placing a forumula down a column using a vlookup formula

Below I am attempting to place the formula just to the right of the last column, beginning at row 2. I know the For statement works, as well as the searching for last column/ row as i've used this in a previous macro when placing a formula down a column. The only question I have is how do I make the VLookup formula work properly?
End goal:
1) Forumla on column to the right of last one
2) Vlookup looksup the value in the last column on the given row within the For statement on a tab called "Lookup"
3) On this Lookup tab, column A is where the value will be found, but I need to return the second column value.
Please zero in on the forumula beginning with the "=iferror(...". I currently receive the error, "Application Defined or Object-Defined" error.
EThree = Cells(Rows.Count, 4).End(xlUp).Row
NumThree = Evaluate("=COUNTA(9:9)")
For r = 2 To EThree
Cells(r, NumThree + 2).Formula = "=IFERROR(((Vlookup(" & Cells(r, 14).Value & ",Lookup!$A:$B,2,0)""))))"
Next
You can place your formula in one go; no need to loop.
Try this:
With Sheets("NameOfWorksheet") '~~> change to suit
'~~> first get the last row and column
Dim lrow As Long, lcol As Long
lrow = .Range("D" & .Rows.Count).End(xlUp).Row
lcol = .Cells(9, .Columns.Count).End(xlToLeft).Column
Dim rngToFillFormula As Range, mylookup As String
'~~> get the lookup value address
mylookup = .Cells(2, lcol).Address(False, False, xlA1)
'~~> set the range you need to fill your formula
Set rngToFillFormula = .Range(.Cells(2, lcol), Cells(lrow, lcol)).Offset(0, 1)
rngToFillFormula.Formula = "=IFERROR(VLOOKUP(" & mylookup & _
",Lookup!A:B,2,0),"""")"
End With
What we did is explained in the comments. HTH.