Vba: vlookup for entire column - vba

I have column B with cost centre codes and column D with department. i need to do a vlookup to fill in the department name of the relevant cost centre code.
The current code is like this:
Dim MyStringVar1= Application.Vlookup(Range("B7"),_
Worksheets("VLOOKUP Table").Range("A2:B1000"),2,True)
However, i dont just want to do vlookup for D7 only but rather the entire column. My range is not fixed(there may be 100 or 200rows in Column B,depending on the number of projects.)
How do I apply the formula for the entire column? Instead of D7 only

let's say you want to add formula =VLOOKUP(B2,'VLOOKUP Table'!A$2:B$1000,2,TRUE)
to range D3:D10, where 'B2' will increment after every row, then the code would be :
Range("D3:D10").Formula= "=VLOOKUP(B2,'VLOOKUP Table'!A$2:B$1000,2,TRUE)"

Dim This As Worksheet
Set This = ThisWorkbook.Sheets(1)
This.Activate
This.Range("D7", Range("A2").End(xlDown).Offset(0, 3)).Formula = "=VLOOKUP(B2,[INSERT SHEET]!$A:$D,2,FALSE)"
If the data is in sheet2, you just insert sheet2 in the [INSERT SHEET]. It doesn't matter if the name is sheet2 or named something else, just call it sheet2

You could use relative references in an R1C1 formula, then just paste it to your destination range, you'd need to find the destination range first, perhaps using something like .end(xldown).row
See this for reference on the general idea:
http://macromatician.blogspot.co.uk/2013/02/how-to-add-formula-to-worksheet-range.html

Related

How to copy/paste formula in filtered/visible cells via VBA in Excel

I am struggling with copying and pasting formula from one column to another one within using filter in another column.
I got a table with 52 columns (number of rows is changing each month).
In column AW (#49) I have applied filter. It shows only CTD.
After applying this filter I need to copy formula from column AH to column AG. Of course I need to apply this only for filtered/visible cells.
The code I have written is copying/pasting this formula into all cells in column AG (it doesn't consider my filter in column AW).
Another problem is that when applying the filter in column AW then the first visible row doesn't need to be all the time AH2 but it can be e.g. AH15 or whatever. I guess this could be avoid via some dynamic solution. Unfortunately I have no clue how to do it.
Afterwards I would like to apply the same for filters in another columns.
Many warm thanks in advance for any hint! :)
This is my code:
Sub ApplyFilterInColumnAW()
Sheets("DATA").Select
ActiveSheet.ListObjects("tb_DATA").Range.AutoFilter Field:=49, Criteria1:="CTD"
Range("AG2").Select 'dynamic solution?
ActiveCell.FormulaR1C1 = "=[#[Service/Log Formula]]" 'header name of column AH
End Sub
Range.Copy and Range.Paste only work on visible cells. In my example I target the cells in the column using the Column Header.
Sub ApplyFilterInColumnAW()
Const TagetColumnLabel = "Test"
Dim tbl As ListObject
Set tbl = Sheets("DATA").ListObjects("tb_DATA")
With Sheets("DATA")
.ListObjects("tb_DATA").Range.AutoFilter Field:=49, Criteria1:="CTD"
tbl.ListColumns(TagetColumnLabel).DataBodyRange.FormulaR1C1 = "=tb_DATA[[#This Row],[Service/Log Formula]]"
End With
End Sub

Excel VBA Compare cell value to list and overwrite value in separate sheet

In a workbook I have, users either manually enter an account code or select one from a list and the account codes are placed in column C (C7:C446) in a sheet called "JE". The account codes look like this ####### - ### - ## - ######. In column D (D7:D446) in sheet "JE", there is a formula that captures the last 6 digits of the account code. In a sheet called "required_refs", there is a list of 6 digit codes in column A. If the value in the D column in sheet "JE" equals any of the values in column A of "required_refs" sheet, I would like the value in the D column cell to overwrite the cell value in cell D1 in a separate sheet called "references" (I know that may have been confusing, sorry)
Example: if the value of D25 matches any of the values listed in column A of sheet "required_refs", upon double clicking a red colored F25 cell, put the value of D25 (of sheet "JE"), and put it in cell D1 on sheet "references".
I've taken a crack at it as best I know how. I've placed this code in sheet JE:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim project As Range: Set project = Range("D7:D446")
Dim param As Range: Set param = Worksheets("references").Range("D1").Value
For Each cell In project
If project.Value = Worksheets("required_refs").Range("A:A").Value Then
Call gotoRef_ 'macro that simply selects/navigates to the required_ref sheet
project.Value = param
End If
End Sub
Thanks so much in advance for any suggestions on how to complete this. I can elaborate on this further if needed.
This will do what you want:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Intersect(Target, Range("F7:F446")) Is Nothing Then Exit Sub
Dim varReference As Variant
varReference = Columns("D").Cells(Target.Row).Value2
If Not IsError(Application.Match(varReference, Worksheets("required_refs").Columns("A"), 0)) Then
Worksheets("references").Range("D1").Value = varReference
End If
End Sub
Important Points:
Whenever working with event handlers, always limit the scope of the target range in the first line. Otherwise, it might not work correctly or it could slow done your spreadsheet.
Make sure your JE sheet column D values and required_refs sheet column A values are all either text or numbers. Otherwise the values won't be compared correctly.
Note the usage of Application.Match() instead of WorksheetFunction.Match() to access the worksheet function. This, coupled with the use of a Variant type variable, allows us to trap the error that occurs if the match fails.
You can always do this on the sheet. Consider the MATCH function. See here for how to use MATCH.
Or another great tool if you're searching for something in a table associated with a value in another column (not your case I don't think)--VLOOKUP formula. Place this formula in the D cell of the sheet you want to place the numbers in. VLOOKUP is in the following format:
=vlookup(lookup value,table_array,column index number, [range lookup])
The lookup value is the 6 digit code you're looking for (on the JE sheet)
The table_array is simply selecting the values you want to search for (required_refs sheet)
The column index number would be one, since the table only has 1 column. It's basically the column number of the value you're looking for.
And range lookup is for if you think there might be more than one place where it matches.
For your case I think it would look like this:
=vlookup('JE'!D1,'required_refs'!A1:A,1,FALSE)
Then just lock the values you want to keep and click and drag down.
Explanation for VLOOKUP here

Excel : Copy and paste multiple rows and columns from one worksheet to another

i would like to copy multiple rows from one worksheet to another , i have data starting in one worksheet at A2 row and ends at A108850 and it starts at A2 column and ends at I2 column , how can i copy all that data into another worksheet where row starts with A4 and column starts with A4 and ends with I4.
How could i possibly do it through some macro?.
Thanks.
Try this
Worksheets("Sheet1").Range("A2:I108850").Copy Worksheets("Sheet2").Range("A4")
Change the range reference and worksheet's name accordingly.
Copy&Paste is an "expensive" operation, the greater the range the more expensive the operation
Should you be interested in values only, you could try this:
Worksheets("DestinationSheetName").Range("A2:I108850").Value = Worksheets("SourceSheetName").Range("A2:I108850").Value
edited after OP's comment
Should the code in your last comment have the same aim of pasting values only, then change the second statement into the following:
With Worksheets("Sheet1").Range("A2:I108850") '<--| reference the "source" range you want to paste values from
.Range("A4").Resize(.Rows.Count, .Columns.Count).Value = .Value '<--| resize "destination" range accordingly to "source" one and paste values into it
End With
of course you must check for sheet names to be valid ones for the currently active workbook

sorting range based on other column values in Excel 2010

I have excel sheet contain data as below:
what we need is sorting range D2:E10 based on Column A values
we need result to be like this:
Is there any method allow us to do that?
(we recommend not to use macro if possible)
the closest solution with no macros is
select column a and d
use conditional fomat -> highlight cells Rules --> duplicated values
now all douplicted values cell color chaned
select range A2:B7 and custom sort using cell color, not colored cells at bottom
do the same with range D2:E10
hope this help you
I find some workaround solution
in cell F2 I used
=VLOOKUP(A2;$D$2:$E$20;1;FALSE)
and in cell G2
=VLOOKUP(A2;$D$2:$E$20;2;FALSE)
copy formulas to range F3: G10
this gives me some result but some data in range D2:E10 lost such as D4, D5 ...etc (not copied in column F and G )

Moving Data between Worksheets based on a key

In both worksheets I have a key in column A. Not all of the key values are in both worksheets.
For each key value in column A of Worksheet 1, I want to find the corresponding key in worksheet 2 and move the data in column B of worksheet 2 into column B of worksheet 1.
I have never programmed a macro so I am completely lost for writing this code.
There is no need for VBA here, Philip.
Try this formula in cell B1 of Sheet1:
=IFERROR(vlookup(A1,Sheet2!A:B,2,false),"")
If you are on XL 2003, then do this:
=IF(ISERROR(vlookup(A1,Sheet2!A:B,2,false)),"",vlookup(A1,Sheet2!A:B,2,false))
Then drag this formula down for the rest of your data in Column A of Sheet1.
NB - Sheet2 is the assumed name of your Worksheet2, you may need to change to fit your needs.
NB2 - you can lookup vlookup in Excel Help (or online) to better understand what it does
Are you sure you need to use a macro for this? It sounds to me like you are using Excel and a simple VLOOKUP formula would do what you need.
A VLOOKUP looks like this: =VLOOKUP(A1,Sheet2!$A:$B,2,FALSE)
Where A1 is your reference cell (in this case you "key" in column A).
Sheet2!$A:$B is the lookup table (in this case columns A and B from the second sheet).
2 is the column number that you want data from, counting from the left (in this case the second column, column B)
FALSE tells the formula to only return values for exact matches. TRUE returns the closest match in the lookup table.