Excel VBA filldown to last row used in previous column - excel

I've been looking all afternoon for the answer to this.
the code works as I want (after lots of time researching, I'm rather green to this) except I'd like to fill down to the last row used in previous column rather than the whole sheet.
I can't give exact referece to the previous column because it isn't always in the same place hence why I am looking it up and doing everything based on that look up result.
All answers I have found use the Range command but I can't find how to use my colNum variable for that.
Sub cndob()
'
' cndob change dob
'
' find column number and select
'
Dim colNum As Integer
colNum = WorksheetFunction.Match("BDate", Range("1:1"), 0)
Columns(colNum + 1).Select
' insert column right
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
' formula fill down
Cells(2, colNum + 1).Select
ActiveCell.FormulaR1C1 = "=RIGHT(RC[-1],2)&CHAR(47)&MID(RC[-1],5,2)&CHAR(47)&LEFT(RC[-1],4)"
Range(ActiveCell, ActiveCell.End(xlDown)).FillDown
Please help

The Range.Offset property is the perfect solution for this. Change your last line of code to:
Range(ActiveCell, ActiveCell.Offset(0, -1).End(xlDown)).FillDown
The first argument to .Offset is the row offset. That we don't want to change. The column offset, though, is set to one to the left of the active column.

I am not sure what exactly do you want to do, but from what I understood, something like this will do the job:
Option Explicit
Sub TestMe()
Dim colNum As Long
Dim sht As Worksheet
Dim rng As Range
Set sht = ActiveSheet
colNum = WorksheetFunction.Match("BDate", Range("1:1"), 0)
Set rng = sht.Cells(1, colNum)
rng.Offset(0, 1).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
rng.Offset(0, 1).FormulaR1C1 = "=1+1"
Range(rng, rng.End(xlDown)).Offset(0, 1).FillDown
End Sub
What it does? It looks for a cell "Bdate" on the first row and if it finds it, it inserts column to the right (if not, it gives an error :)). After this, it inserts a formula 1+1 for each cell, which is to the right. Anyhow, something like this:

Related

Selecting cell by adjacent column name

I am very new to VBA and am trying to create a macro that selects the cell next to a specifically named column, names it "UniqueID", has it apply a concatenate formula to the whole column, and then selects the next column over, names it "VerifyID", and has it apply a VLOOKUP to the whole column. What I'm having issues with is having the specific cell selection work. Here is what I have:
Application.CutCopyMode = False
Sheets("PowerBI Data Dump").Select
Selection.AutoFilter
Dim i As Long
Dim LastSamplePrepColumn As Range
Dim rngHeaders As Range
Set rngHeaders = Range("1:1")
Set LastSamplePrepColumn = rngHeaders.Find("UniqueID")
i = LastSamplePrepColumn.Column
j = LastSamplePrepColumn.Column + 1
ActiveSheet.Cells(2, i).Select
ActiveCell.FormulaR1C1 = "=CONCATENATE(RC[-2],RC[-1])"
Selection.AutoFill Destination:=Range("RC2:RC157")
ActiveSheet.Cells(1, j).Select
ActiveCell.FormulaR1C1 = "VerifyID"
ActiveSheet.Cells(2, j).Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],UniqueID!C[-26],1,FALSE)"
When debugging, it errors at the last line. My main issue, however, is with having the Range().Select choosing columns by letter instead of by the name of the column. I get data dumps in a variety of formats, so I need it to be able to select a column by the name of the one next to it.
Thanks in advance for any advice.
Edit: I have changed my code to reflect where I am now. I'm still stuck on how to make the formula apply to the whole column without selecting the column by letter.
So you want to find the 'UniqueID' column and then add formulas in the two columns to the right and copy then down?
This code will do that but I think you might need to rethink the VLOOKUP formula.
For a start you can probably replace it with MATCH and if the column UniqueID is going to be in you might want to consider changing the relative column reference, i.e. -26, to an absolute reference.
Dim wsData As Worksheet
Dim LastSamplePrepColumn As Range
Dim rngHeaders As Range
Dim colID As Long
Application.CutCopyMode = False
Set wsData = Sheets("PowerBI Data Dump")
Set rngHeaders = ws.Range("1:1")
colID = Application.Match("UniqueID", rngHeaders, 0)
If Not IsError(colID) Then
With wsData
.Range(.Cells(2, colID + 1), .Cells(.Rows.Count, colID).End(xlUp).Offset(, 1)) _
.FormulaR1C1 = "=CONCATENATE(RC[-2],RC[-1])"
.Range(.Cells(2, colID + 2), .Cells(.Rows.Count, colID).End(xlUp).Offset(, 2)) _
.FormulaR1C1 = "=VLOOKUP(RC[-1],UniqueID!C[-26],1,FALSE)"
End With
End If

Find end of variable range

I am new to VBA and have been struggling with finding a solution to copying & pasting some formulas into a range with a variable end row. I managed to cobble together the below code, which works, but it is inefficient because it pastes the formulas one row at a time. I would like to copy the formulas and then paste them into the entire range at once (instead of row by row). I have to do this function in a few different sheets and ranges so ideally I'd like to create a sub routine to find the last row. What I don't know is 1) how to find the last row 2) how to reference it when I'm selecting the range to paste the formulas into.
The sheet is setup with data in the first column, starting in cell C9, and the formulas are in D8:I8. I need to copy the formulas into the range of D9.I? (with the last row being the last row of data in column C).
I've been working on this for about 5 hours and am going out of my mind. Any help would be appreciated!
Sample of the code I have managed to write that works but isn't efficient:
Range("D8").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
ActiveCell.Offset(1, -1).Select
Do Until ActiveCell.Value = Empty
ActiveCell.Offset(0, 1).Select
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
ActiveCell.Offset(0, -1).Select
ActiveCell.Offset(1, 0).Select
Loop
The classic way to find the last used row is shown below. Call the function like Debug.Print LastRow or, directly in the Immediate Window, with ? LastRow
Function LastRow() As Long
With ActiveSheet
LastRow = .Cells(.Rows.Count, "A").End(XlUp).Row
End with
End Function
Observe that both, the .Rows.Count and the result are taken from the ActiveSheet and that the measure is taken in column "A". (You can replace the name "A" with the number 1 in the above formula). If you want to develop the function, pass both the sheet and the column to it as arguments.
.Cells(.Rows.Count, "A") defines the cell A1400000 (or thereabouts), the last cell in the column. Then the function looks for the first occupied cell above that, meaning that if A1 and A10 are in use and A2:A9 are blank, the function will return 10. It's important to understand that .Cells(.Rows.Count, "A").End(XlUp) is a range object, a cell, of which the .Row property holds the number of the row where that range is located.
Now, if you want to define a range D9:I? you might do it like this, setting the range by defining its first and last cell. Observe the 4 leading periods. Each one stands for the object in the With statement, in this case ActiveSheet.
With ActiveSheet
Set MyRange = .Range(.Cells(9, "D"), .Cells(.Rows.Count, "I").End(xlUp))
End With
But that would take the measure for the last used cell in column I. Often it's the first column on the left that is longer than the last column in the required range. In that case you might use code as shown below.
With ActiveSheet
Set MyRange = .Range(.Cells(9, "D"), .Cells(.Rows.Count, "D").End(xlUp))
End With
With MyRange
Set MyRange = .Resize(.Rows.Count, 9)
End With
The code first sets the range for column D only, presuming that column D is the longest one, and then expands it to include 9 columns. Observe the .RowsCount refers to the ActiveSheet in the first With block and to MyRange in the second.
Of course, you could achieve a similar result with this code which calls the LastRow function (which measures the last row in column A):-
With ActiveSheet
Set MyRange = .Range(.Cells(9, "D"), .Cells(LastRow, "I"))
End With
This solution is a Subroutine to fill a range with values (in this case, formulas) and find the LastRow in a separate Function. There are many ways to do this so feel free to modify it how you please.
First this Subroutine receives the relevant Worksheet, range the formulas are in and the Column letter for the start and end of our destination range.
The Sub uses the Range.AutoFill method to fill the destination range, much the same as if you click the bottom right of a cell with a value and drag up/down/left/right to fill the cells in that direction.
Public Sub AutoFillVariableSizedRangeByRow _
(ByRef TargetWorkSheet As Worksheet, _
ByVal TargetValueCellAddress As String, _
ByVal StartColumn As String, _
ByVal EndColumn As String)
Dim RangeValuesArray As Variant
Dim TargetValueCell As Range
Dim TargetRange As Range
Set TargetValueCell = TargetWorkSheet.Range(TargetValueCellAddress)
Set TargetRange = TargetWorkSheet.Range(StartColumn & Right(Mid(TargetValueCellAddress, 4), 1) & ":" & _
EndColumn & LastRow(TargetWorkSheet, "C"))
TargetValueCell.AutoFill TargetRange
End Sub
The LastRow is found by a separate function, which is well explained already in many places on the net, including another answer to this question.
Public Function LastRow(ByRef TargetSheet As Worksheet, ByVal TargetColumnLetter As String) As Long
LastRow = TargetSheet.Cells(Rows.Count, TargetColumnLetter).End(xlUp).Row
End Function
To write the LastRow function with excel references (not user defined variables), it would look like:
Sheet1.Cells(Rows.Count, "C").End(xlUp).Row
To call the sub it could look something like:
Private Sub myProcedure()
AutoFillVariableSizedRangeByRow ThisWorkbook.Sheets("Sheet1"), "D1:I1", "D", "I"
End Sub
In the above, ThisWorkbook.Sheets("Sheet1") is TargetWorkSheet and "D1:I1" is TargetValueCellAddress, "D" and "I" are the start and end columns of our destination range respectively.
In this example, I've put values 1 to 20 down column C and the formula =$C1*$C1 in row 1 of columns D to I, all on Sheet1.
And here is the output after running AutoFillVariableSizedRangeByRow Sheet1, "D1:I1", "D", "I":
As example, the formula across row 8 is =$C8*$C8 and row 20 is =$C20*$C20.

Inserting copied cells then referencing back to original cells using replace function

I am currently trying to write a macro that essentially takes a column,duplicates it to the right, then changes certain references to refer back to the previous column.
I am using the replace method, but because i am looking for a specific string based on the column letter and "2" I used an object to bring together the column letter and the "2".A better way to explain is say I copied column B and inserted it and made a duplicate in column C.
I now want to find "C2 and "C3" in my formulas and change them to "B2" and "B3".
I figured this would be done by finding the aforementioned strings by using the replace method and offsetting them by -1. This has proved rather difficult. Any ideas?
'duplicates column over 1'
ActiveCell.EntireColumn.Select
Selection.Copy
ActiveCell.Offset(0, 1).EntireColumn.Select
Selection.Insert Shift:=xlToRight
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone
Application.CutCopyMode = False
'Declarations and Instantiations'
Dim rngo As Range, cell As Range, ranger As Range
Dim lookfor As String
Dim UsedRng As Range, LastRow As Long
Set rngo = Selection.EntireColumn
Set UsedRng = ActiveSheet.UsedRange
LastRow = UsedRng(UsedRng.Cells.Count).Row
rngo.Select
Do Until ActiveCell.Row = LastRow + 1
For Each cell In rngo
Col = SPLIT(ActiveCell(1).Address(1, 0), "$")(0) 'returns just the cell letter'
lookfor = (Col & "2") 'combines the column letter with the number(I BELIEVE THIS IS THE SOURCE OF THE ISSUE BUT IM NOT SURE IN WHAT WAY'
'starts to search the new column for "lookfor" which is just the designated string'
rngo.Replace _What:=lookfor, Replacement:="'offset lookfor by 1 column'",_SearchOrder:=xlByRows, MatchCase:=True
Next cell
ActiveCell.Offset(1, 0).Select
Loop
MsgBox ColumnName(Selection)
MsgBox lookfor
End Sub
Solved: change " rngo.Replace" to "ActiveCell.Replace"

Trouble with an Excel VBScript, Referencing A Relational Cell Address

Okay, I'm learning scripting for Excel and I've come across something that I just don't know how to do.
I've been asked to help automate the import of a sheet into a sheet and then add some columns off to the side and do some calculations and autofill them to the last row of the imported info. That is no problem. I recently found out however that the sheet that I would import for my office has X number of columns and other offices have Y and Z number of columns in the sheets that they would import. So I'm trying to do this to where it builds the calculation columns at the end of the imported columns. With that bit of background here's where I need some assistance:
Script as written for my office and works:
Range("O1").Select
ActiveCell.FormulaR1C1 = "Remainder"
Range("O2").Select
ActiveCell.FormulaR1C1 = "=MOD(RC[-14],RC[-5])"
Range("O2").Select
Range("O2").AutoFill Destination:=Range("O2:O" & Cells(Rows.Count, "B").End(xlUp).Row)
So now I need to make this relational not Cell Address Specific So I came up with this.
Range("A1").select
Selection.End(xlToRight).Select
ActiveCell.Offset(0, 1).Select
ActiveCell.FormulaR1C1 = "Threshold"
ActiveCell.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "=IF(RC[-13]>(RC[-5]/3),""Over"",""Under"")"
Range(ActiveCell.Address).AutoFill Destination:=Range(*****How to return the Current Cell Address** : **How to Return the Current Column Letter***** & Cells(Rows.Count, "B").End(xlUp).Row)
I've Tried "ActiveCell.Address":"CHAR(COLUMN()+64))" but That doesn't work and I Just don't know how to get it to set that value to Be the equivalent ?2:? my office running this should autofill from O2:O. But would return P2:P in another.
I'm assuming you want the formula to go in the 1st unused column, no matter how many columns there are. (This will allow for future column use, as well.)
Dim LastCol as integer
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column + 1
Cells(1, LastCol).FormulaR1C1 = "Remainder"
Cells(2, LastCol).FormulaR1C1 = "=MOD(RC[-14],RC[-5])"
Cells(2, LastCol).AutoFill Destination:=Range(Cells(2, LastCol), _
Cells(Cells(Rows.Count, "B").End(xlUp).Row, LastCol))
How's this:
Sub test()
Dim lastCol As Integer, lastRow As Integer, formulaCol As Integer
Dim ws As Worksheet
Set ws = ActiveSheet
' First, let's find the last column (#) and last row (#)
With ws.UsedRange
lastCol = .Columns.Count
lastRow = .Rows.Count
End With
' Now, create the "header, two columns offset from last column"
formulaCol = lastCol + 2
Cells(1, formulaCol).Value = "Remainder"
'Now, let's create a range, that we will fill with the MOD() formula. You can do this _
through resizing a range, instead of selecting and autofill
With ws
.Range(.Cells(2, formulaCol), .Cells(2, formulaCol)).Resize(lastRow - 1, 1).FormulaR1C1 = _
"=IF(RC[-" & formulaCol - 1 & "]>(RC[-2]/3),""Over"",""Under"")"
End With
End Sub
I am assuming a few things: Your raw sheets come with the data in one block. In other words, you don't have a gap of columns between data you need. This will get the last used column and row, and use those to enter your formula.
Also, I assume that you are checking that the first part of your mod() formula refers to the info in Col. A, and the second part is the right most column's data. I think I'm not understanding something, so any more info. about how the data is laid out would be helpful. But also, this avoids using "Select", which is good VBA practice from what I've gathered.

Excel Macro Repetitive IF and Else

I am currently working on an Excel VBA Macro script where in it will do a simple TRUE or False test to the active cell. My problem is, i cannot make this working until the end of the list. It only run once and ends the program. I need this VB script to perform the IF & ELSE test up to the bottom of the list.
Description of the problem:
Let's say i have a list of dates in A1 to A9999 and beside it (F1:F9999) there's also a list that has a text on it. the F1:F9999 list contains two values only. (a)SAME DATE and (b) NOT THE SAME.
Perform a True or False test in the List F1:F9999.
If the active cell value is equal to the text "SAME DATE" (TRUE), it will ignore and move to the next item in the list then perform again number 1.
If the active cell value is equal to the text "SAME DATE" (FALSE), it will insert a row above it and then move to the next item in the list then perform again number 1
The TRUE or FALSE test will run until the end of the list.
The TRUE or FALSE test will stop running if it reached the bottom of the list.
by the way, the number of items in the list is not consistent. I just put there F1:F9999 for example purposes.
here's my code!
Sub IFandElseTest()
If ActiveCell.Value = "Same Date" Then
Range(Selection, Cells(ActiveCell.Row, 1)).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
ActiveCell.Offset(1, 0).Select
Else:
ActiveCell.Offset(1, 0).Select
Range(Selection, Cells(ActiveCell.Row, 1)).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End If
End Sub
Appreaciate if you could help me on this.
Give this a try.
Explanation:
You should avoid using .Select/ActiveCell etc. You might want to see this LINK
When working with the last row, it's better not to hard code values but dynamically find the last row. You might want to see this LINK
Work with Objects, what if the current sheet is not the sheet with which you want to work with?
The below FOR loop will traverse the row from below and move up.
Code:
Sub Sample()
Dim ws As Worksheet
Dim LRow As Long, i As Long
Dim insertRange As Range
'~~> Chnage this to the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
'~~> Work with the relevant sheet
With ws
'~~> Get the last row of the desired column
LRow = .Range("E" & .Rows.Count).End(xlUp).Row
'~~> Loop from last row up
For i = LRow To 1 Step -1
'~~> Check for the condition
'~~> UCASE changes to Upper case
'~~> TRIM removes unwanted space from before and after
If UCase(Trim(.Range("E" & i).Value)) = "SAME DATE" Then
'~~> Insert the rows
.Rows(i).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End If
Next i
End With
End Sub
Screenshot:
Followup From Comments
It really worked! BUT, one final modification. in your code: Set ws = ThisWorkbook.Sheets("Sheet1") Is it possible is you can set the WS as the Active worksheet. The reason of this is because the name of the worksheet unique and not consistent also.
Like I mentioned, in the first link above as well in the comment, do not use Activesheet. Use CodeNames of the sheet which do not change. See the screenshot below.
Blah Blah is the name of the sheet which you see in the worksheet tab but Sheet1 is the CodeName which will not change. i.e. you can change the name of the sheet from Blah Blah to say Kareen but in the VBA editor, you will notice that the Codename doesn't change :)
Change the code
Set ws = ThisWorkbook.Sheets("Sheet1")
to
'~~> Replace Sheet1 with the relevant Code Name
Set ws = [Sheet1]
Edit:
If you leave out the r.copy line it does more or less exactly what Siddharth Rout's solution does
Sub insrow()
Dim v, r As Range
Set r = [d1:e1]
v = r.Columns(1).Value
Do
' r.copy
If v = "Same Date" Then r.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Set r = r.Offset(1)
v = r.Columns(1).Value
Loop Until v = ""
End Sub
This does not yet include the end condition if row exceeds line 9999 but that should be easy to add ...

Resources