Master Dataset- Sheet1
Sub Dataset- Sheet2
Similar to the question on If and Loop function to extract data, I have two worksheets. I am trying to use VBA to input Column M for me- the x's. For example, to the left of apple should be 123, as it is its code, and orange 456 etc., according to the Master Dataset. Because it is a similar problem as the one on the aforementioned site, I tweaked the code a little, but it would not work. It is as follows:
Option Compare Text
Sub DataExtraction()
Dim SrchRng As Range, cel As Range, rngDest as Range
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
'restrict the search range
Set SrchRng = Application.Intersect(ws1.Range("F;F"), ws1.UsedRange)
Set rngDest = ws2.cells(rows.count, 1).end(xlUp).Offset(1, 0) 'start copy here
For Each cel In SrchRng.Cells
If cel.value=rngDest.value Then
rngDest.offset(0, -1).value = cel.offset(0, -1).value
Set rngDest = rngDest.offset(1, 0) '<< next row down
End If
Next cel
End Sub
In short, I am trying to tell VBA that if the Fruit of interest matches, then input the Code found in Column D of Sheet1 into Column M of Sheet 2 accordingly, then move to the next row and repeat the exercise. Any help would be greatly appreciated.
P.S. A very special thanks to Tim Williams for solving my problem previously, and hitherto helping me to set up this model that I used to develop.
There is an easy solution without using VBA. You could do that with formulas too with a combination of MATCH() and INDEX(). This should even be faster.
Just use
=INDEX(Sheet1!D:D,MATCH(N:N,Sheet1!F:F,0))
If you need to automate it, I would write this formula into column M (and if necessary convert the formulas into values):
Option Explicit
Public Sub FillInCodes()
Dim wsSub As Worksheet
Set wsSub = ThisWorkbook.Worksheets("Sheet2")
Dim LastRow As Long
LastRow = wsSub.Cells(wsSub.Rows.Count, "A").End(xlUp).Row
wsSub.Range("M2:M" & LastRow).Formula = "=INDEX(Sheet1!D:D,MATCH(N:N,Sheet1!F:F,0))"
'and if you need to convert the formulas into values
wsSub.Range("M2:M" & LastRow).Value = wsSub.Range("M2:M" & LastRow).Value
End Sub
Related
I have the following worksheet:
I want to convert the range from C15 to last row/column to array.
I have tried the following code but is not working:
Sub rangeToArray()
Dim arr() As Variant
arr = Range("C15", Range("C15").End(xlDown).End(xlToRight))
End Sub
I get this:
Could someone help me please with this? I would like to get the range from C15 to last row/column and based on different criteria to sort it and copy rows to a different spreadsheet with the same format. I want to convert the range into an array as I have over 30k rows and will work faster.
Thank you!
arr = Range("C15", Range("C15").End(xlDown).End(xlToRight)) is just another way of saying arr = Range("C15").CurrentRegion
On top of that this would currently refer to the ActiveSheet, therefor you might want to try the following:
Sub rangeToArray()
Dim arr() As Variant
With Sheet1 'Change to whichever CodeName your sheet has
arr = .Range("C15").CurrentRegion
End With
End Sub
Note: As said in my comment, CurrentRegion will not work correctly once you start having gaps in your data. Therefor you might want to rework the code to check for the last used row in column C:C and the last used column in row 15:
Sub rangeToArray()
Dim arr() As Variant
Dim lr As Long, lc As Long
With Sheet1 'Change to whichever CodeName your sheet has
lr = .Cells(.Rows.Count, 3).End(xlUp).Row
lc = .Cells(15, .Columns.Count).End(xlToLeft).Column
arr = .Range(.Cells(15, 3), .Cells(lr, lc))
End With
End Sub
Based on this answer with the most reliable way to find the last row and column, the following range is possibly the most reliable way to select all your data to last row and column:
Arr = Range(Cells(15, 3), Cells(Range("A" & Rows.Count).End(xlUp).Row, _
Cells(1, Columns.Count).End(xlToLeft).Column))
Please note, it would be best to specify the sheet for every Cell and Range statement.
I understand how to use the offset function for a dynamic range, but what if that dynamic range is within a specific number of additional columns? For example, say I have a worksheet with columns A:N, and the named range refers to D2:E2. If I add two more columns, that range should expand to D2:G2, but not include columns F and onward.
I'm currently using the offset function with the counta function to do this, but there are a number of natural blank cells within this range (because of merged cells). Is there a way for me to remove these blanks for use in the combobox's dropdown?
Currently I've defined the name as:
=OFFSET('Sheet 1'!$D$2,0,0,1,COUNTA('Sheet 1'!$D2:$ZZ2))
Which returns all of the values I'm looking for, but several blanks as well that I don't want in the dropdown.
I'm currently using the following code during the userform's initialization, but this doesn't seem to be working either:
Dim Rng As Range
Dim i As Long
Me.ComboBox1.RowSource = ""
Set Rng = Range("Combo")
For i = 1 To Rng.Rows.Count
If Rng(i) <> "" Then
Me.ComboBox1.AddItem Rng(i)
End If
Next i
I've also tried
Dim aCell As Range, ws1 As Worksheet, lastColumn As Long, stopColumn As Long
Set ws1 = Worksheets("sheet 1")
With ws1
lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
stopColumn = lastColumn - 12
Me.ComboBox1.RowSource = ""
With ws1
For Each aCell In .Range("D2", .Cells(2, stopColumn))
If aCell.Value <> "" Then
Me.ComboBox1.AddItem aCell.Value
End If
Next
End With
Neither attempt has worked though, the combobox dropdown is empty.
The second part of the code above actually was functional, I was just using the wrong procedure name. I was using UserForm2, and had renamed the initialize procedure Private Sub UserForm2_Initialize() when it should have instead been `Private Sub UserForm_Initialize()
This is quite simple, I am aware, but something is going wrong for me. I simply want to subtract the values I have in column B from the values I have in column C and place these results in column Q.
I have assigned my strFormula(1) as a variant and then applied the equation to the strFormula(1). I have altered the following code from #Manhattan here on Stack Overflow :)
Sub FormulasNoLoops()
Dim strFormulas(1) As Variant
With ThisWorkbook.Sheets("Sheet1")
strFormulas(1) = "=(C2-B2)"
.Range("Q2:Q130").Formula = strFormulas
.Range("Q2:Q130").FillDown
End With
End Sub
There is no error when I run the script but also no result in column Q.
Ideally, I do not even want to enter the last cell of the column but maybe use .End(xlUp) somewhere.
Thanks all!
first
Dim strFormulas(1) As Variant
is creating an array with two items, 0,1
For one formula I would avoid the variable totally.
But if you want to use it just make it a string without the (1)
Dim strFormulas As String
Then load it:
strFormulas = "=(C2-B2)"
Also when you apply the formula to the whole range there is no need to fill down:
Sub FormulasNoLoops()
With ThisWorkbook.Sheets("Sheet1")
.Range("Q2:Q130").Formula = "=(C2-B2)"
End With
End Sub
Sub test()
Dim lastrow As Long
Dim rng As Range
last_row = ThisWorkbook.Worksheets("sheet1").Cells(Rows.Count, 1).End(xlUp).Row
Set rng = Range("C2:C" & last_row)
rng.Formula = "=B2-A2"
End Sub
I'm really new to programming and I have a spreadsheet I'm working on that I could use some help with. My Columns A and B are two dropdown menus, where B is dependent on A. There are some other columns that use VLookUp to bring up information based on the dropdown, and one other column where I have a simple formula. If I clear out a value from Column "A", I would like the entire row to clear (without losing my formulas), and i would all the cells with values under it to shift up. I've looked up a lot of ways to do this with deleting cells, but I haven't been able to find much with clearing them. My code almost works, but seems pretty inelegant since I'm using the clipboard. I also need to clear out the last row at the end using this code, but when I try it, Excel crashes. Any advice would be most appreciated. Here is my code so far:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim wks As Worksheet
Dim FirstRow As Long
Dim FirstColumn As Long
Dim LastRow As Long
Dim QtyColumn As Long
Dim FormulaRange1 As Range
Dim FormulaRange2 As Range
FirstColumn = 1
QtyColumn = 4
Set wks = ActiveSheet
If Not Application.Intersect(Target, Range("A11:A26")) Is Nothing Then
If IsEmpty(Target.Value) Then
wks.Range("B" & Target.Row).ClearContents
wks.Range("D" & Target.Row).ClearContents
FirstRow = Cells(Target.Row, Target.Column).Row
LastRow = Cells(Rows.count, 1).End(xlUp).Row
Set FormulaRange1 = wks.Range(Cells(Target.Row, Target.Column).Offset(1, 0), wks.Cells(LastRow, "B"))
Set FormulaRange2 = wks.Range(Cells(Target.Row, "D").Offset(1, 0), wks.Cells(LastRow, "D"))
FormulaRange1.Copy
wks.Range(Cells(FirstRow, FirstColumn).Address).PasteSpecial xlPasteValues
FormulaRange2.Copy
wks.Range(Cells(FirstRow, QtyColumn).Address).PasteSpecial xlPasteValues
Application.CutCopyMode = False
End If
End If
End Sub
I have an Excel Sheet with values going in each column from cells 2:21
I need to highlight the corresponding cell in each column with the maximum value and try to loop through it with a macro. But I only know how to do it for a given hard-coded range..
Private Sub Worksheet_Activate()
Dim zelle As Range
For Each zelle In ActiveSheet.Range("B2:B21")
If zelle.Value = Application.WorksheetFunction.Max(Range("B2:B21")) Then
zelle.Interior.ColorIndex = 6
Else
zelle.Interior.ColorIndex = xlNone
End If
Next
End Sub
I tried to use a new range for column which I gave the Range ("B:IT") and iterate through that one but that didnt work.
Maybe it's just 2 or 3 lines?
This might work for you. Instead of using hard-coded ranges, it loops through whatever columns are used and adjusts for columns having different "lengths". It assumes a single header row and column.
Private Sub Worksheet_Activate()
Dim zelle As Range
Dim rng As Range
Dim lCol As Long
Dim lLastRow As Long
With ActiveSheet
For lCol = 2 To .UsedRange.Columns.Count
lLastRow = .Cells(.Rows.Count, lCol).End(xlUp).Row
Set rng = .Range(.Cells(2, lCol), .Cells(lLastRow, lCol))
For Each zelle In rng
If zelle.Value = Application.WorksheetFunction.Max(rng) Then
zelle.Interior.ColorIndex = 6
Else
zelle.Interior.ColorIndex = xlNone
End If
Next
Next lCol
End With
End Sub
An alternative way to do this is without VBA, is to
Calculate the maximum value e.g. at the bottom (=MAX(A1:A10)) and
To use conditional formatting, highlighting the cell(s) that match the result of your =MAX(A1:A10) calculations.
I know that the question referred to VBA, but this makes it dynamic and VBA independent.
Use variables:
Range(Cells(row_var_1, col_var_1),Cells(row_var_2, col_var_2))
Where row_var_1, col_var_1, row_var_2 and col_var_2 are variables that may be iterated in your loop.