I got this code from another answer on here and it is better than they way I was doing it because you can actually just select where you are pulling your file from. But it seems like I can't get the file name exactly correct in the VLOOKUP? I get error 1004 right after the VLOOKUP. Maybe there is something else wrong. I copied this code then replaced what I needed but I need another pair of eyes. Thanks in advance.
Dim x As String
Dim lNewBracketLocation As Long
x = Application.GetOpenFilename( _
FileFilter:="Excel Files (*.xls*),*.xls*", _
Title:="Choose previous quarter's file", MultiSelect:=False)
MsgBox "You selected " & x
'Find the last instance in the string of the path separator "\"
lNewBracketLocation = InStrRev(x, Application.PathSeparator)
'Edit the string to suit the VLOOKUP formula - insert "["
x = Left$(x, lNewBracketLocation) & "[" & Right$(x, Len(x) - lNewBracketLocation)
Range("V2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP($E2,'" & x & "]file_2017072732'!$B$5:$AP$9486,18,FALSE)"
' ERROR 1004
Selection.AutoFill Destination:=Range("V2:V177")
Range("V2:V177").Select
When I get to that point it shows that x is equal to "C:\Name\Name\Name\[Filename.xlsx".
Is that the format it should be?
The issue is not with the value of x, which looks like it is in a valid format.
The problem lies with assigning a formula, written using A1 notation, to a cell using its FormulaR1C1 property.
Change
ActiveCell.FormulaR1C1 = "=VLOOKUP($E2,'" & x & "]file_2017072732'!$B$5:$AP$9486,18,FALSE)"
to either
ActiveCell.Formula = "=VLOOKUP($E2,'" & x & "]file_2017072732'!$B$5:$AP$9486,18,FALSE)"
or
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC5,'" & x & "]file_2017072732'!R5C2:R9486C42,18,FALSE)"
and it should be OK.
Related
I am using this code down below to use a VLOOKUP in another file that you select using the GetOpenFilename. I want shtName to be the name of the sheet in the file that you select, but whenever I step through it, it is always the name of the sheet that I am working in and putting the VLOOKUP in.
I have shtName in my VLOOKUP and it doesn't show anything when I step through it. X shows the filename and path, but shtName right after shows nothing. But my VLOOKUP ends up working anyway and it puts the sheet in the formula.
Why is that? I want to be able to do it myself and so I know I get the sheet name from the file you are selecting.
Dim iRet As Integer
Dim strPrompt As String
Dim strTitle As String
' Promt
strPrompt = "Please select the last Kronos Full File before the dates of this HCM Report." & vbCrLf & _
"This will be used to find the Old Position, Org Unit, and Old Cost Center." & vbCrLf & _
"For example, if the date of this report is 7-28-17 thru 8-25-17, the closest Kronos Full File you would want to use is 7-27-17."
' Dialog's Title
strTitle = "Last Kronos Full File for Old Positions"
'Display MessageBox
iRet = MsgBox(strPrompt, vbOK, strTitle)
Dim LR As Long
Dim X As String
Dim lNewBracketLocation As Long
X = Application.GetOpenFilename( _
FileFilter:="Excel Files (*.xls*),*.xls*", _
Title:="Choose the Kronos Full File.", MultiSelect:=False)
MsgBox "You selected " & X
'Find the last instance in the string of the path separator "\"
lNewBracketLocation = InStrRev(X, Application.PathSeparator)
'Edit the string to suit the VLOOKUP formula - insert "["
X = Left$(X, lNewBracketLocation) & "[" & Right$(X, Len(X) - lNewBracketLocation)
shtName = ActiveWorkbook.Worksheets(1).name
LR = Range("E" & Rows.Count).End(xlUp).Row
Range("T2").Formula = "=VLOOKUP($E2,'" & X & "]shtName'!$B$1:$AP$99999,15,0)"
Stop
Range("T2").AutoFill Destination:=Range("T2:T" & Range("E" & Rows.Count).End(xlUp).Row)
Stop
Range("T2:T" & Range("E" & Rows.Count).End(xlUp).Row).Select
Stop
Range("U2").Formula = "=VLOOKUP($E2,'" & X & "]shtName'!$B$1:$AP$99999,41,0)"
Range("U2").AutoFill Destination:=Range("U2:U" & Range("E" & Rows.Count).End(xlUp).Row)
Range("U2:U" & Range("E" & Rows.Count).End(xlUp).Row).Select
Range("V2").Formula = "=VLOOKUP($E2,'" & X & "]shtName'!$B$1:$AP$99999,18,0)"
Range("V2").AutoFill Destination:=Range("V2:V" & Range("E" & Rows.Count).End(xlUp).Row)
Range("V2:V" & Range("E" & Rows.Count).End(xlUp).Row).Select
Cells.Select
Cells.EntireColumn.AutoFit
Something like the following should give you the worksheets name out of a file
Dim wbk As Workbook
Set wbk = Workbooks.Open(Filename:="YOUR_FILE_PATH", ReadOnly:=True)
Dim shtName As String
shtName = wbk.Worksheets(1).Name
wbk.Close
Note: We can open the workbook in read only mode if we don't plan to change anything.
Additionally I recommend (for a good code following good practices):
Always specify a worksheet.
Eg for every Range("") like Worksheets("YourSheetName").Range("")
Or use With statements:
With Worksheets("YourSheetName")
.Range("A1").Value = 5 'recognize the starting full stop referring to the with statement
End With
Same for every Rows, Columns, Cells, etc.
Avoid using .Select, .Activate and Selection. at all.
(there are many tutorials out there in the Internet how to avoid them).
Use Option Explicit and declare all your variables before use.
(avoids many issues, especially typos).
I'm trying to get a macro to type out a heap of formulae for me. The formula goes something like this:
=COUNTIF('other_sheet'!A:A,"hello*")
The user can specify A and other_sheet, so I select the cell and then go
ActiveCell.Value = "=COUNTIF('" & othercell & "'!" & column & ":" & _
column & """,hello*"")"
But it keeps giving me errors like:
1004: Object Defined Error
I have tried using ActiveCell.Text, ActiveCell.Formula etc. and they all don't work.
It needs to be ActiveCell.Formula and ", is the wrong way around next to Hello. It should be:
ActiveCell.Formula= "=COUNTIF('" & othercell & "'!" & column _
& ":" & column & ",""hello*"")"
Apparently you can only put proper, completed answers into a cell.
i.e. if the output turns out to be "=sum(A:A" and a bracket isn't closed, then the application throws an error just as if you typed it in manually.
I'm trying to apply a big nested formula to a range using the code below. Basically, if the value in cell A of the active row exists in the column A of another workbook and if the cell in column E of the active row is not empty, I want the active cell to display the cells to display the value of the equivalent cell in a separate workbook.
This needs to be applied to several worksheets so I'm using the variables lrow (which is an int with the last row of the active worksheet in workbook#1) and tlrow (which is an int equal to the last row of the active worksheet in workbook#2). When I step through the sub, these variables both return the numbers I would expect them to.
Likewise, this is inside of a for loop so I also use Worksheets(i).Name where I is an int.
When I run the code, I get the run-time error "'1004': Application-defined or object-defined error".
I'm assuming it's a syntax issue.
Code:
Range("B15:B" & lrow).FormulaR1C1 = _
"=IF(OR(RC1="""",RC5=""""),"""",IF(ISERROR(VLOOKUP(RC1,'[temp.xlsx]" & _
Worksheets(i).Name & _
"'!A15:D" & tlrow & ",3,FALSE)),""0"",VLOOKUP(RC1,'[temp.xlsx]" & _
Worksheets(i).Name & "'!A15:D" & tlrow & ",3,FALSE))))"
Try using this:
Range("B15:B" & lrow).FormulaR1C1 = _
"=IF(OR(RC1="""",RC5=""""),"""",IF(ISERROR(VLOOKUP(RC1," & _
Worksheets(i).Range("A1:D" & lrow).Address(ReferenceStyle:=xlR1C1, External:=True) & _
",3,FALSE)),""0"",VLOOKUP(RC1," & _
Worksheets(i)..Range("A1:D" & tlrow).Address(ReferenceStyle:=xlR1C1, External:=True) & _
",3,FALSE)))"
What version of Excel are you running? In more recent versions you can use the Iferror function in this formula to really chop down the size.
It would be something like this:
Range("B15:B" & lrow).FormulaR1C1 = _
"=IF(OR(RC1="""",RC5=""""),"""",IFERROR(VLOOKUP(RC1," & " & Worksheets(i).Range("A1:D" & _
tlrow).Address(ReferenceStyle:=xlR1C1, External:=True) & ",3,0),""0"")"
Thanks for your help. I was able to resolve the problem by defining my vlookup range in a Range variable and then inputting the variable name in L42's equation in place of
worksheets(i).Range("A1:D" & lrow)
Really apprecaite the responses! Thanks again.
Recently I created Macros which searched through column B using a text match and populated column H with "Y" or "N" depending on whether there was a match or not. The code used was as follows.
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
.Range("H2:H" & lRow).FormulaR1C1 = "=IF(C[-6] = ""Commodities Ags/Softs"", " & _
"(IF(RC[-3]=R1C24,""Y"",(IF(RC[-3]=R2C24,""Y""," & _
"(IF(RC[-3]=R3C24,""Y"",(IF(RC[-3]=R4C24,""Y""," & _
"(IF(RC[-3]=R5C24,""Y"",(IF(RC[-3]=R6C24,""Y""," & _
"(IF(RC[-3]=R7C24,""Y"",(IF(RC[-3]=R8C24,""Y""," & _
"(IF(RC[-3]=R9C24,""Y"",""N"")))))))))))))))))),"""")"
Range("H2:H" & lRow).Select
Selection.Copy
ActiveSheet.Range("H2:H" & lRow).PasteSpecial xlPasteValues
I had to write 7 different macros because of the 7 possible matching texts in column B and the data I was matching it to comes from 7 different sources. I.E. If I received data from Commodities Ags/Softs, I would run the Commodities Ags/Softs macro (the other macros are identical, just swapping the text).
Now I've been told the data will be expanding to 70 different sources with 70 potential matching texts, rendering my specific macro to specific data approach pretty useless.
I was wondering if anyone knows how I could generalise the macro and in doing so, create a textbox which would tell the macro what text to match in column B.
Basically, I was hoping that if I received data from a particular source, I could run the macro, a textbox would appear in excel and whatever I typed into it would be the text I'm trying to match in column B, effectively altering the generalised macro.
Any help would be greatly appreciated, I'm new to VBA,
Cheers!
Basically:
Dim sMatch as String
sMatch = InputBox("Enter match data")
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
With .Range("H2:H" & lRow)
.FormulaR1C1 = "=IF(C[-6] = """ & sMatch & """, " & _
"(IF(RC[-3]=R1C24,""Y"",(IF(RC[-3]=R2C24,""Y""," & _
"(IF(RC[-3]=R3C24,""Y"",(IF(RC[-3]=R4C24,""Y""," & _
"(IF(RC[-3]=R5C24,""Y"",(IF(RC[-3]=R6C24,""Y""," & _
"(IF(RC[-3]=R7C24,""Y"",(IF(RC[-3]=R8C24,""Y""," & _
"(IF(RC[-3]=R9C24,""Y"",""N"")))))))))))))))))),"""")"
.Value = .Value
End With
I have been assigned the task of developing a excel document that whole office will use. The user will click a button and the macro will export the file as a PDF to a shared folder. I wrote this code and tested this code using excel 2010. People that have excel 2007 where getting an error message saying "Run Time Error 1004 Document not saved. This document may be open, or an error may have been encountered when saving." I looked into the problem a little bit and found that excel 2007 needed an add-in update, so I installed it on their computers. I also checked to see if they have adobe on their computers and they do. They are still having the problem and I am unsure of what to do. Any help would be greatly appreciated!
Here is my code
' Define all variables
Dim strFileName As String
Dim folder As String
Dim member As Integer
Dim member_count As Integer
Dim member_name As String
Dim show As Variant
Dim MyTime As String
'Save as new file
Worksheets("Input data").Visible = True
folder = Sheets("Input data").Range("location").Value
MyTime = Time
Sheets("Input data").Select
Range("G2").Value = MyTime
strFileName = folder & "Material Request - " & Sheets("Input data").Range("name").Value & "_" & Sheets("Input data").Range("date").Value & " " & Sheets("Input data").Range("time").Value & ".pdf"
Sheets("Material Request").Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFileName 'OpenAfterPublish:=True`
You should start with changing the code to remove .Select & .ActiveSheet instances.
Dim oWS as Worksheet
Set oWS = ThisWorkbook.Worksheets("Input data")
' Worksheets("Input data").Visible = True
folder = oWS.Range("location").Value
If Right(folder,1) <> Application.PathSeparator Then folder = folder & Application.PathSeparator
MyTime = Time
' Sheets("Input data").Select
oWS.Range("G2").Value = MyTime
strFileName = folder & "Material Request - " & oWS.Range("name").Value & "_" & oWS.Range("date").Value & " " & oWS.Range("time").Value & ".pdf"
Debug.Print "strFileName: " & strFileName
'Sheets("Material Request").Select
oWS.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFileName 'OpenAfterPublish:=True`
Set oWS = Nothing
Refer to this MSDN Worksheet.ExportAsFixedFormat Method, you may need fill in more parameters depending on properties of the Worksheet "Input Data".
I have added some checks and refer to Immediate window to check value of strFileName in 2007.
I had a similiar problem (Error 1004 when attempting export). After an hour of pulling my hair out, here was the source of my problem.
I was passing a cell value as part of generating the filename. I was doing this in the format of
fileName:= ActiveWorkbook.Path & "\" & CStr(Workbooks.Cells(i,j).Value) & ".pdf"
The text in the cell itself was formatted to be in two rows (i.e. "top row text" + (Alt+K) + "bottom row text"). While the string looks normal in Debug.print, MsgBox, or value previews, I am thinking that there is a hidden character which encodes the new line for the cell. I believe this hidden character causes the error when passed as part of the fileName argument. I'm guessing Excel doesn't pick it up but the OS's file name system does.
In any case, this fixed the issue for me.