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
Related
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.
i am trying to copy and paste unique values of a column in vba. the challenges are the: the excel doesn't have a fixed position, the position can change based on the data. As can be seen in the picture, i want to take the unique values of the amount(abs) of Columns A and paste then besides it on columns B, i don't want to touch the amounts in column A. there are a couple of empty cells between amount and absolute amount. both amount and absolute amounts are dynamic.
enter image []1 here
As i mentioned above, the tables are dynamic. if the number of amount gets bigger the amount adds a new row and the amount(abs) always keeps the two empty cells between. Any suggestions help is apperciated?
you could use RemoveDuplicates() method of Range object:
Sub Test()
With Worksheets("MySheetName") ' change "MySheetName" to your actual sheet name
With .Range("A1", .Cells(.Rows.Count, 1).End(xlUp))
With .Range(.Find(What:="Amount(ABS)", LookIn:=xlValues, LookAt:=xlWhole).Offset(1), .Cells(.Count))
.Offset(, 1).Value = .Value
.Offset(1).RemoveDuplicates Columns:=1, Header:=xlNo
End With
End With
End With
End Sub
If you have access to the UNIQUE function in excel:
Determine your range of ABS Amounts using the defined variables Found and lr
Output the UNIQUE function to the right to de-dup your range
Clear the formula/spill range with a value transfer (Range.Value = Range.Value)
Sub Social_Distance()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet2") '<-- Update Sheet Name
Dim Found As Range, lr As Long
lr = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
Set Found = ws.Range("A1:A" & lr).Find(What:="Amount(ABS)", LookIn:=xlValues, LookAt:=xlWhole)
If Not Found Is Nothing Then
Found.Offset(, 1) = "Unique Values"
Found.Offset(1, 1) = "=UNIQUE(" & ws.Range(ws.Cells(Found.Offset(1).Row, 1), ws.Cells(lr, 1)).Address(False, False) & ")"
ws.Range(ws.Cells(Found.Offset(1).Row, 2), ws.Cells(lr, 2)).Value = ws.Range(ws.Cells(Found.Offset(1).Row, 2), ws.Cells(lr, 2)).Value
End If
End Sub
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"
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.
I have a list of references of cells to be deleted. The list of references is in sheet "test_url". The list of references point to cells to be deleted that are in another sheet "main_lists".
What I am after is a macro that takes all the references listed in "test_url" sheet, and select their cells in "main_lists" sheet and delete them.
The following macro is what I recorded for two references only in an attempt to demonstrate my problem that necessitated me to copy the reference from "test_url" sheet, then paste it in the NameBox of "main_urls" sheet to select the contents of the designated cell then delete its contents. This process was done manually one cell at a time for a list of 10-20 addresses/references. However, recently this list is over 2000 entries and it is growing:
Sub DeletePermittedCells()
'DeletePermittedCells Macro
Sheets("test_urls").Select
Range("B2").Select
Sheets("test_urls").Select
Selection.Copy
Sheets("main_lists").Select
Application.Goto Reference:="R200045C1"
Application.CutCopyMode = False
Selection.ClearContents
Sheets("test_urls").Select
Range("B3").Select
Selection.Copy
Sheets("main_lists").Select
Application.Goto Reference:="R247138C1"
Application.CutCopyMode = False
Selection.ClearContents
Sheets("test_urls").Select
End Sub
Can someone help with this issue please?
Try this one:
Sub DeletePermittedCells()
Dim rng As Range
Dim arr, c
With Sheets("test_urls")
'storing data in array makes your code much faster
arr = .Range("B2:B" & .Cells(.Rows.Count, "B").End(xlUp).Row).Value
End With
With Sheets("main_lists")
Set rng = .Range(arr(1, 1))
For Each c In arr
Set rng = Union(rng, .Range(c))
Next
End With
rng.ClearContents
End Sub
storing addresses in array (rather than reading each cell from worksheet directly) makes your code much faster.
Note, code assumed that your addresses stored in range B2:B & lastrow where lastrow - is row of last cell with data in column B
This assumes that the list of cells to be cleared in is column A:
Sub ClearCells()
Dim s1 As Worksheet, s2 As Worksheet
Dim N As Long, I As Long, addy As String
Set s1 = Sheets("test_url")
Set s2 = Sheets("main_lists")
N = s1.Cells(Rows.Count, "A").End(xlUp).Row
For I = 1 To N
addy = s1.Cells(I, 1).Value
s2.Range(addy).ClearContents
Next I
End Sub