VBA Insert function VLOOKUP into range,lookup range in other workbook. The file containing the lookup table is achieved using filename_AcctMgr = Application.GetOpenFilename(, , "Select Acct Mgr File", "Select"), then opening the file. Let's call this workbook2.
In workbook1 I am adding the VLOOKUP formula into "F2" and looking up Column "A" values in workbook2, columns A:C. I Then copy the formula to all rows of column "F".
I cannot find the syntax required to properly reference the workbook2 range in columns A:C.
ActiveCell.Formula = _
"=VLOOKUP(activecell.offset(0,-5).address,'ws.name'!A:C,3,FALSE)"
Can anyone suggest the proper syntax?
Try this:
Range("F2").Resize(10).Formula = "=VLOOKUP(A2,[Book2]Sheet1!$A:$C,3,FALSE)"
Or
Range("F2:F10").Formula = "=VLOOKUP(A2,[Book2]Sheet1!$A:$C,3,FALSE)"
EDIT: Sorry I forgot the piece about the filename as a variable:
Dim MyFile As String
Dim vSplit As Variant
Dim iCnt As Integer
MyFile = Application.GetOpenFilename(, , "Select Acct Mgr File", "Select")
vSplit = Split(MyFile, "\")
iCnt = UBound(vSplit)
vSplit(iCnt) = "[" & vSplit(iCnt) & "]"
MyFile = Join(vSplit, "\")
Range("F2:F10").Formula = "=VLOOKUP(A2,'" & MyFile & "Sheet1'!$A:$C,3,FALSE)"
You will need to add error handling in case someone clicks cancel. Also I doubt you want to add the formula to all rows in column f so just define the range you want. My examples is rows 2 to 10.
I am assuming you want the name of the sheet / range to be in a variable, rather than hard-coded. As it it, you have the name of the variable in the middle of your string, but it will be treated as a string, not a variable containing a string.
I suggest that you do something like the following:
Dim sheetName, lookupFrom, myRange ' always declare your variables
sheetName = "This is the sheet name" ' note I added some spaces to make it challenging
lookupFrom = ActiveCell.Offset(0, -5).address
myRange = "'" & sheetName & "'!A:C" ' putting quotes around the string so it's always valid
ActiveCell.Formula = "=VLOOKUP(" & lookupFrom & "," & myRange & ", 3, FALSE)"
You can of course do this all at once - it just gets messy to look at:
ActiveCell.Formula = "=VLOOKUP(" & ActiveCell.Offset(0, -5).Address & ", '" & sheetName & "'!A:C, 3, TRUE)"
Further note - the sheetName can of course contain the name of the other workbook - but you need name of workbook AND sheet... so
sheetName = "[Book2]Sheet1"
would be fine.
In your example you used ws.name (without proper quoting) - but that would not have given you the full path since you need both the workbook and the worksheet name to make sure you reference the right data. Better be explicit - if Excel can make the wrong assumptions about what you want, it will - and you will be left scratching your head...
Since you actually showed you had opened the book, you have the name of the file (the workbook) in your variable filename_AcctMgr. Then you should be able to use:
sheetName = "[" & filename_acctMgr & "]Sheet1"
and take it from there.
Related
This is the part I currently have:
Worksheets("Data").Cells(3, CRup).FormulaR1C1 = "=VLOOKUP(RC[-7],'[" & TOD & "]" & flt & "'!R1C1:C18, " & CRupT & ",0)"
Try this vba function Application.WorksheetFunction.VLookup
Example :
Dim lk_Val = 'Lookup Value String'
Worksheet("DestinationSheet").Range("A1") = WorkApplication.WorksheetFunction.VLookup(lk_Val,Workbooks("YourSourceWorkbook").Sheets("YourSourceSheet").Range("A:B"),2,False)
As far as i know the workbook must be opened
Note : I'm French, so normally I use french functions (e.g. SI for IF or SOMME for SUM) and the default decimals separator is the coma and not the point (e.g. 1,03 for 1.03)
I have to replace many formulas in an Excel workbook, and all of them have the same template, but I could not use the fast fill-in tool, so I'm trying to make a macro for this.
First, here is how the cell currently looks :
='C:\...\[file1.xlsx]'sheeta!$XXa$nna - 'C:\...\[file2.xlsx]'sheetb!$XXb$nnb
So basicely, I want to keep these two addresses (I will name them ad1 and ad2) to make the followig formulas :
=IF(AND(ISNUMBER(VALUE(ad1;"."));ISNUMBER(VALUE(ad2;".")));SUM(VALUE(ad1,".");PRODUCT(-1;VALUE(ad2;".")));"NA")
Which substracts two numbers stored with differents formats, and displays NA if at least one of them is not a number.
Here is the macro I wrote :
Sub tmp()
Dim c As Range
Dim adr1 As String
Dim adr2 As String
Dim frm As String
For Each c In Application.Selection.Cells
adr1 = Split(Split(c.Formula, "=")(1), "-'")(0)
adr2 = "'" & Split(Split(c.Formula, "=")(1), "-'")(1)
frm = "=IF(AND(ISNUMBER(VALUE(" & adr1 & ";"".""));ISNUMBER(VALUE(" & adr2 & ";""."")));SUM(VALUE(" & adr1 & ";""."");PRODUCT(-1;VALUE(" & adr2 & ";""."")));""NA"")"
c.Formula = frm
Next
End Sub
The error occures on the last action c.Formula = frm.
I've already checked frm's value, and it is good.
I think there is a synthax error on my formula, but I couldn't find it. Can someone help me ?
Thanks in advance !
VBA accept only US format formula. US format use , instead ;
frm = "=IF(AND(ISNUMBER(VALUE(" & adr1 & ",""."")),ISNUMBER(VALUE(" & adr2 & ","".""))),SUM(VALUE(" & adr1 & ","".""),PRODUCT(-1,VALUE(" & adr2 & ","".""))),""NA"")"
I'm trying to simplify a file_split script to a point of self-service in my dept. No one really has any understanding of the language, so I was checking to see if any of this could be further simplified so coworkers don't have to update the code from the editor pane.
for instance, I have things like Basepath to designate where the files will be saved off. How can I change
Dim Basepath As String
Basepath = "C:\Users\File Cuts\"
directory as string
to something like this where a user can select a folder pathway?
Dim Basepath as filedialog
with basepath
.title = "Select save location"
.directory = .selecteditems(1)
end with
and then instances where I have specific columns to reference (target value columns for each new file, naming convention columns, etc...)
as in:
Dim Manager_Name, Login_ID, Leader
Manager_Name = SourceData(i,4)
Login_ID = SourceData(i,5)
Leader = SourceData(i,9)
to be inputted by an input box for column letter like:
Dim column_selection as variant
column_selection = InputBox("Enter Column Letter")
Manager_Name = SourceData(i,column_selection)
There are quite a few references that I'd like to see if I could change so that edits could be made without actually touching the code (the column ranges where variants like name, and login ID will be changing a lot)
rest of code:
Option Explicit
Sub File_Splits()
Dim Wb As Workbook
Dim SourceData, Mgr_Name, Login_Id
Dim i As Long, j As Long, k As Long, a As Long
Dim Destination_Cell As Range
Dim Basepath As String, strNewpath As String, strLeader As String
Basepath = "C:\File Cuts\" '1. paste in file save pathway, keep last \
Set Wb = Workbooks.Open("C:\File_Split_Mgr_Template.xlsx") '2. paste template ws address here
Set Destination_Cell = Wb.Worksheets("Manager Data").Range("A2") '3. Update worksheet name and target cell
With ThisWorkbook.Worksheets("Roster")
SourceData = .Range("I10", .Range("A" & Rows.Count).End(xlUp)) '4. change I10 to your last column letter, dont change the number(keep the 10)
End With
Wb.Activate
Call Speed_Up_Code(True)
For i = 1 To UBound(SourceData)
If SourceData(i, 5) <> Login_Id Then '5. change the 1 to login column #
If i > 9 Then
Destination_Cell.Select
strNewpath = Basepath & strLeader & "\" 'comment this out if folders aren't needed
If Len(Dir(strNewpathD, vbDirectory)) = 0 Then 'comment this out if folders aren't needed
MkDir strNewpath 'comment this out if folders aren't needed
End If 'comment this out if folders aren't needed
Wb.SaveCopyAs strNewpath & _
ValidFileName(Login_Id & "_" & Mgr_Name & "_File Name.xlsx") '6. update file name
End If
With Wb.Worksheets("Manager Data") '7. change to template sheet
.Rows(2 & ":" & .Rows.Count).ClearContents '8. change 2 to row after header(s)--if header isn't in row 1
End With
Mgr_Name = SourceData(i, 4) '9. change 1 to mgr name column
Login_Id = SourceData(i, 5) '10. change 2 to login ID column
strLeader = SourceData(i, 9) '11. change 5 to lvl 3 mgr column
j = 0
End If
a = 0
For k = 1 To UBound(SourceData, 2)
Destination_Cell.Offset(j, a) = SourceData(i, k)
a = a + 1
Next
j = j + 1
Next
If Len(Dir(strNewpath, vbDirectory)) = 0 Then
MkDir strNewpath
End If
SaveCopy Wb, strNewpath, Login_Id, Mgr_Name
Call Speed_Up_Code(False)
End Sub
Public Sub SaveCopy(Wb As Workbook, strNewpath As String, Login_Id, Mgr_Name)
Wb.SaveCopyAs strNewpath & _
ValidFileName(Login_Id & "_" & Mgr_Name & "_File Name.xlsx") '12. update file name
End Sub
Have you considered having a sheet called something like "Configuration" where users write to and your script can read from. Hidden or protected if necessary
For example, list all your configuration description in col A, and the user fills in the value next to in col B, So if A1 contains the text "Manager Name Column [A-Z] =" the user enters the value "D" or 4 in cell B1. The script become Mgr_Name = SourceData(i, wsConfig.range("B1")). I guess you could add validation to their entries.
Layout the sheet like a form in logical groups and highlight where the entry cells are. In a case like entering column names I would put them horizontal with the descripting above and entry cell below, that seems more natural. Protect all the cells except the highlighted ones.
I am writing a vlookup function and I want to reference the last tab in a another workbook, rather than the tab name as it changes daily.
To move to the last tab in the workbook I have
Sheets(Sheets.Count).Select
Is it possible to reference this in the a VLOOKUP? (left a blank where the worksheet should be)
"=VLOOKUP(RC[133],'[Unavista UTI Lookup December2019.xlsm]" "'!C4:C7,4,0)"
This is just off the top of my head (untested), but maybe something like this
Dim wbData as Workbook
Set wbData = Workbooks.Add("Unavista UTI Lookup December2019.xlsm")
ActiveWorkbook.Worksheets("Sheet1").Range("A1").Formula = "=VLOOKUP(RC[133],[" & wbData.Name & "]" & wbData.WorkSheets(wbData.WorkSheets.Count).Name & "!C4:C7,4,0)"
wbData.Close False
Alternatively, using the .Open method:
Dim wbData as Workbook
Set wbData = Workbooks.Open(Filename:="Unavista UTI Lookup December2019.xlsm", ReadOnly:=True)
ActiveWorkbook.Worksheets("Sheet1").Range("A1").Formula = "=VLOOKUP(RC[133],[" & wbData.Name & "]" & wbData.WorkSheets(wbData.WorkSheets.Count).Name & "!C4:C7,4,0)"
wbData.Close False
Adjust Sheet1 and A1 to your needs
But still, you would need to trigger this code on an event of some sort, which isn't clear to me yet.
The Function I am at is below;
Currently i am changing the date of the worksheet which the vlookup is referencing. So the below shows "Dec 9" from yesterday. Once the new tab gets created today in the file "Unavista UTI Lookup December2019" - It will show "Dec 10"
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(RC[133],'[Unavista UTI Lookup December2019.xlsm]Dec 9'!C4:C7,4,0)"
What I am trying to do is find a way for the code to automatically change this to todays date. Speaking with someone at work we tried the below
Dim DayValue As String
Dim FormulaString As String
DayValue = Format(Date, "mmm d")
Range("E2").Select
FormulaString = "=VLOOKUP(EH2,'[Unavista UTI Lookup December2019.xlsm]" & DayValue & "' !$D:$G,4,0)"
The formula isn't bringing back any error, but unfortunately the lookup isn't doing anything, and just bringing back empty cells.
If anyone can resolve this, as i've tried numerous things and still not been able to get it to work.
I would assume that your were applying the formula with a line like this:
Range("E2").Formula = FormulaString
however when I tried that line, it returned an error as your line has one blank space in excess, as the syntax for a link with another workbook should be:
'[WorkbookName]WorksheetName'!Range
and your line has:
'[WorkbookName]WorksheetName' !Range
Therefore instead of this:
FormulaString = "=VLOOKUP(EH2,'[Unavista UTI Lookup December2019.xlsm]" & DayValue & "' !$D:$G,4,0)"
use this:
FormulaString = "=VLOOKUP(EH2,'[Unavista UTI Lookup December2019.xlsm]" & DayValue & "'!$D:$G,4,0)"
Range("E2").Formula = FormulaString
However, in order to ease the maintenance of the procedure I suggest to use a constant, try this procedure:
Sub Formula_Today()
Const kFml As String = "= VLOOKUP( RC[133]," & _
"'[Unavista UTI Lookup December2019.xlsm]#TODAY'!C4:C7, 4, 0 )"
Dim sFml As String
sFml = Replace(kFml, "#TODAY", Format(Date, "mmm d"))
With ThisWorkbook.Worksheets("DATA")
.Range("E2:E10").FormulaR1C1 = sFml
End With
End Sub
Before adding the new worksheet
After adding the new worksheet and applying the Formula_Today procedure
I was tasked with creating a code that will check to see if internal hyperlinks in an excel spreadsheet worked. This code first changes the formulas that were on the spreadsheet and makes them actual hyperlinks (they were originally formulas linking the locations together). The problem that I have now is that I want to create hyperlinks ONLY if Column S has text. If it doesn't, I don't want the "E-COPY" text to be displayed. All of the text in Column S varies (not one line has the same characters), which is why I'm drawing a blank is to how I tell the program to only continue if it has any text, not anything specific. I am working with Excel 2016.
Also, I am doing this to 71935 and counting rows; is there a limit to how many it can go through? If so, what can I do about it?
Thank you!
Sub CreateHyperlinks()
Dim FN As Variant
Dim Path As Variant
Dim count As Variant
Sheets(1).Activate
count = WorksheetFunction.CountA(Sheets(1).Range("A:A"))
For i = 2 To count
If Range("AM" & i).Value = "Yes" And Columns("S") = Then
Range("E" & i).Value = ""
Path = Sheets(1).Range("R" & i).Value
FN = Sheets(1).Range("S" & i).Value
Sheets(1).Range("E" & i).Select
Selection.ClearFormats
Selection.Hyperlinks.Add Anchor:=Selection, Address:=Path & FN, TextToDisplay:="E-COPY"
Range("AM" & i).Value = " "
End If
Next i
End Sub
If you just need to check for any content in ColS then:
If Range("AM" & i).Value = "Yes" And Len(Range("S" & i).Value) > 0 Then
Few things:
'make a reference to the sheet you're working with
Dim ws As Worksheet
Dim wb As Workbook
Set wb = Excel.Application.ThisWorkbook
Set ws = wb.Worksheets(1)
'gets the absolute last row with data in it // ignores empty cells
count = ws.UsedRange.Rows.Count
personally, i hate working with named ranges, so i would suggest setting range references like so
what you wrote
Path = Sheets(1).Range("R" & i).Value
what i believe it should look like
Path = ws.Cells(i, 18).Value
if you want to test the type when working with variants, try this:
'tests the type associated with the variant. an 8 = string
If VarType(ws.Cells(i, 19).Value) = 8 Then
'do your thing
'tests if the value is null
ElseIf VarType(ws.Cells(i, 19).Value) = 0 Then
'do your other thing
here's a list of the vartype enumeration to help you out.
hope it helps!