Select multiple ranges with VBA - excel

I need to select multiple ranges in a worksheet to run various VBA code on them. The ranges will always begin on row 84 but the end depends on how far down the data goes. I've been selecting these ranges separately using code like this:
Sub SelectRange()
Dim LastRow As Integer
LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Range("A84:B" & LastRow).Select
End Sub
That works fine, but I can't figure out how to select multiple ranges at once. I've tried everything I can think of:
Range("A84:B", "D84:E", "H84:J" & LastRow).Select
Range("A84:B,D84:E,H84:J" & LastRow).Select
Range("A84:B & LastRow,D84:E & LastRow,H84:J & LastRow").Select
Nothing works. I get a run-time error when running any of those.

Use UNION:
Dim rng as Range
With ActiveSheet
set rng = Union(.Range("A84:B" & LastRow),.Range("D84:E" & LastRow),.Range("H84:J" & LastRow))
End With
rng.select
But if you intend on doing something with that range then skip the .Select and just do what is wanted, ie rng.copy

Put your dis-continued range address in the first argument of Range object.
For example, Range("A:A,D:D").Select will select column A and column D.
In your case, you may try:
Dim str As String, LastRow As Integer
LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
str = "A84:B" & LastRow & ",D84:E" & LastRow & ",H84:J" & LastRow
Range(str).Select

Range("A84:B & LastRow & "," & "D84:E & LastRow & "," & "H84:J & LastRow").Select

Related

Changing column value based on another column using vba in excel

I am trying to create a macro button that will help me update the the value in the AE column to "N" if the value in the same row of the H column is "REPO".
I am not sure why my code doesn't work properly and just seems to select the AE column when I run it instead of changing the values to "N"
Sub Change_Repo_Risk_to_N()
Sheets("expo").Select
Dim LastRow As Long
Dim i As Long
LastRow = Range("H" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
If Range("H" & i).Value = "REPO" Then
Range("AE" & i).Value = "N"
End If
Next i
End Sub
Probably mistake due to one if these 3:
Lack of Trim()
Lack of UCase() (Option Compare Text is an alternative of this one)
Select() is too slow and does not refer correctly to the worksheet (try to avoid it)
Try this one:
Sub ChangeRepoRiskToN()
With Worksheets("expo")
Dim lastRow As Long
Dim i As Long
lastRow = .Range("H" & Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Trim(UCase(.Range("H" & i).Value)) = "REPO" Then
.Range("AE" & i).Value = "N"
End If
Next i
End With
End Sub

VBA, Fill up/down rows to align with last row

I am trying to delete rows till it meets my last row OR fill down rows to align with last row.
Sometimes my sheet will be like below where I need to delete rows to align with my last row number.:
However sometimes my sheet will be like below, where I need to fill down other columns:
Is there a function that can do this? I am finding it hard to determine when to fill up or fill down.
Thanks
keeping in mind the well known caveats of the use of UsedRange, you could give it a try
Dim lastRow As Long
With ActiveSheet ' <- change it to your actual sheet reference
With .UsedRange
lastRow = .Rows(.Rows.Count)
End With
End With
Please test the next code. It assumes that the reference column will be the seventh one and the one to check the 0 formulas value to be the sixth one. Your picture does not contain the columns header...
Sub DeleteRowsOrFillDownDiscontinuous()
Dim sh As Worksheet, lastR As Long, lastR1 As Long, lastCol As Long
Set sh = ActiveSheet
lastR = sh.Range("F" & rows.count).End(xlUp).row
lastR1 = Range("E" & rows.count).End(xlUp).row
lastCol = sh.cells(lastR1, Columns.count).End(xlToLeft).Column
If lastR < lastR1 Then
sh.rows(lastR + 1 & ":" & lastR1).EntireRow.Delete xlUp
ElseIf lastR > lastR1 Then
sh.Range("A" & lastR1, "E" & lastR1).AutoFill _
Destination:=sh.Range("A" & lastR1, sh.Range("E" & lastR))
sh.Range("G" & lastR1, "AG" & lastR1).AutoFill _
Destination:=sh.Range("G" & lastR1, "AG" & lastR)
sh.Range("AI" & lastR1, sh.cells(lastR1, lastCol)).AutoFill _
Destination:=sh.Range("AI" & lastR1, sh.cells(lastR, lastCol))
Else
MsgBox "Nothing te be processed. Everything aligned..."
End If
End Sub
Edited:
Adapted the code for F:F column as reference, AH:AH not changeable, too and existing columns to be processed after AH Column.
Please test it and send some feedback.

How to use variables in a VBA code using the sumif function

I download a data set that always has a different number of rows. I store two columns as variables, the imports and the months. Then I need to run a Sumif formula that sums the value of imports by the months. I am writing a Sumif formula that uses the two variables and references the cell to its left.
The cells however vary in location based on the changing size of the data set. So I write a code to select the last active cell on a column and select the cell 3 rows down.
When writing the formula with the variables and the cell its giving me an error. Please help sorry for any typos fist time doing this.
I select all the active cells in range D and store them as months, I do the same for the imports. Then using range I find the last active cell on column M, and use select the cell 3 rows down, where I wish to write my formula.
Please see my codes to see what am I doing wrong, I am a novice coder.
Sub Importaciones()
'
' Importaciones Macro
'
Dim LastRow As Long
LastRow = Range("L" & Rows.Count).End(xlUp).Row
Dim Months As Long
Months = Range("D2", Range("D2").End(xlDown)).Select
Dim Imports As Long
Imports = Range("M2", Range("M2").End(xlDown)).Select
Dim LastRowM As Long
LastRowM = Range("M" & Rows.Count).End(xlUp).Row
Range("M" & LastRowM + 3).Formula = "=sumif(" & Months & ", " &
Range("L" & LastRow + 3) & ", " & Imports & ")"
End Sub
For the formula to work and the sum of the month that I choose comes up
As per all the comments:
Sub Importaciones()
With Worksheets("Sheet1") 'Change to your sheet
Dim LastRow As Long
LastRow = .Range("L" & .Rows.Count).End(xlUp).Row
Dim Months As Range
Set Months = .Range("D2", .Range("D2").End(xlDown))
Dim Imports As Range
Set Imports = .Range("M2", .Range("M2").End(xlDown))
Dim LastRowM As Long
LastRowM = .Range("M" & .Rows.Count).End(xlUp).Row
.Range("M" & LastRowM + 3).Formula = "=sumif(" & Months.Address(0, 0) & ", " & .Range("L" & LastRow + 3).Address(0, 0) & ", " & Imports.Address(0, 0) & ")"
End With
End Sub

want to convert Excel formula into VBA code

I wanted to convert below formula to VBA code.
=C1&"`"&K1&"`"&L1&"`"&J1
=VLOOKUP(M1,Data!$A:$J,9,)
=SUMPRODUCT(SUMIF(B1:B,B1,G1:G))
Currently i have enter this formula in 1st row and than copying this formula till the last row used which is taking lot time to apply formula because it has more than million row.
LR1 = Sheets("CRIMS").UsedRange.Rows.Count
Sheets("CRIMS").Range("M1:P1").AutoFill Destination:=Sheets("CRIMS").Range("M1:P" & LR1)
is there any way to convert this formula into VBA code?
For first formula the easiest way would be:
Range("M" & i).FormulaR1C1 = "=RC[-10]&""`""&K&""`""&L&""`""&J"
But for vlookup I prefer dictionaries/collections! It is much much faster.
If You have source data in Data sheet and You want to put that to CRIMS sheet to column M:
Sub vlookup()
Dim names As Range, values As Range
Dim lookupNames As Range, lookupValues As Range
Dim vlookupCol As Object
Dim lastRow As Long
Dim lastRow2 As Long
Dim objekt as Object
With Sheets("Data")
lastRow = Sheets("Data").Cells(Rows.Count, 1).End(xlUp).row
Set names = Sheets("Data").Range("A1:A" & lastRow)
Set values = Sheets("Data").Range("I1:A" & lastRow)
End With
Set objekt = BuildLookupCollection(names, values)
With Sheets("CRIMS")
lastRow2 = 1000000
Set lookupNames = .Range("M1:M" & lastRow)
Set lookupValues = .Range("N1:N" & lastRow)
End With
VLookupValues lookupNames, lookupValues, objekt
Set objekt = Nothing
End Sub
Function BuildLookupCollection(categories As Range, values As Range)
Dim vlookupCol As Object, i As Long
Set vlookupCol = CreateObject("Scripting.Dictionary")
On Error Resume Next
For i = 1 To categories.Rows.Count
Call vlookupCol.Add(CStr(categories(i)), values(i))
Next i
On Error GoTo 0
Set BuildLookupCollection = vlookupCol
End Function
Sub VLookupValues(lookupCategory As Range, lookupValues As Range, vlookupCol As Object)
Dim i As Long, resArr() As Variant
ReDim resArr(lookupCategory.Rows.Count, 1)
For i = 1 To lookupCategory.Rows.Count
resArr(i - 1, 0) = vlookupCol.Item(CStr(lookupCategory(i)))
Next i
lookupValues = resArr
End Sub
Quotation Marks need to be doubled in VBA
Try this:
For i = 1 To LR1
Range("M" & i).Formula = "=C" & i & "&""`""&K" & i & "&""`""&L" & i & "&""`""&J" & i
Range("N" & i).Formula = "=VLOOKUP(M" & i & ",Data!$A:$J,9,)"
Next i
(replace column letters with actual target column)
As mentioned in the comments Looping in this case is highly inefficient.
Use this Code to insert the formulas all at once. It still takes some time for 1 Milion rows though.
Range("M1:M" & LR1).Formula = "=C:C & ""`"" & K:K & ""`"" & L:L & ""`"" & J:J"
Range("N1:N" & LR1).Formula = "=VLOOKUP(M:M,Data!$A:$J,9,)"

Auto-filing Formula to Last Row of a Single Column

I need to constantly start at cell R2 and auto-fill a formula down to the last row of column R. However, the number of rows is constantly changing so I need to write a macro that finds the last row and stops their. I've tried this code but keep getting errors. Any thoughts?
Sub InvoicePrice()
Dim Lastrow As Long
Lastrow = Range("R" & Rows.Count).End(xlUp).Row
Range("R2").Select
ActiveCell.FormulaR1C1 = "=RC[-2]/RC[-4]"
Selection.AutoFill Destination:=Range("R2" & Lastrow)
The error you are getting is due to this Range("R2" & Lastrow)
The range address concatenates to R21400 if the last row was 1400. So we need to add the :R to the address.
Range("R2:R" & Lastrow)
It will now concatenate to R2:R1400
There is not need to do it with three lines, one will suffice:
Sub InvoicePrice()
Dim Lastrow As Long
Lastrow = Range("P" & Rows.Count).End(xlUp).Row
Range("R2:R" & Lastrow).FormulaR1C1 = "=RC[-2]/RC[-4]"
End Sub
Not sure if you already tried this:
Sub InvoicePrice()
Dim Lastrow As Long
Lastrow = Range("P2").End(xlDown).Row
Range("R2").Select
ActiveCell.FormulaR1C1 = "=RC[-2]/RC[-4]"
Selection.AutoFill Destination:=Range("R2" & Lastrow)
It seems to me that Range("R" & Rows.Count) locates you out of current region

Resources