I posted another question that was close to this question earlier but it is actually different. I have this VLOOKUP code that takes input from a user to get the file to use the VLOOKUP with. It works in my one macro when I run the whole thing, but if I run the private sub by itself, I get an error message 1004 on the first VLOOKUP line. I then tried changing the code to use FormulaR1C1, and it ended up working correctly using that version. Why won't it work using my current code but it works when I use FormulaR1C1?
Sub NEWTRY()
'
' Create_VLOOKUP_Using_Old_Kronos_Full_File Macro
'
'
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)
Dim wbk As Workbook
Set wbk = Workbooks.Open(Filename:=X, ReadOnly:=True)
Dim shtName As String
shtName = wbk.Worksheets(1).name
wbk.Close
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("T2").FormulaR1C1 = "=VLOOKUP(RC11,'" & X & "]'!R3C2:R9846C49,13,0)"
ActiveWorkbook.ActiveSheet.Range("U2").Formula = "=VLOOKUP($E2,'" & X & "]'!$B$1:$AP$99999,41,0)"
Range("V2").Formula = "=VLOOKUP($E2,'" & X & "]shtName'!$B$1:$AP$99999,18,0)"
The issue is I believe in the last 3 lines, or how it is reading X and putting that in there. The last 3 lines with the VLOOKUPS is where it errors except now the first line with R1C1 actually works. I was trying other versions with the other lines but they don't work.
I would rather not use the R1C1 but it doesn't want to work unless I use it.
So, you're trying to do a lookup on a sheet whose name is the last part of the selected path?
Add a line msgbox x before your lookups so you can make sure that x is being calculated as you intended... For me it returned:
c:\path\[filename.xlsm
What is an example of x ?
...the 3 formulas getting pasted in are:
=VLOOKUP(RC11,'c:\path\[filename.xlsm]'!R3C2:R9846C49,13,0)
=VLOOKUP($E2,'c:\path\[filename.xlsm]'!$B$1:$AP$99999,41,0)
=VLOOKUP($E2,'c:\path\[filename.xlsm]shtName'!$B$1:$AP$99999,18,0)
Related
I am getting this error 1004 when trying to use this vlookup. I use a window to select a file then that file is used in the vlookup. I do it in another macro I have and I used basically the same code. But for some reason this one is not working. Can anyone see any glaring issues? I cannot figure out what I am doing wrong.
I get the error on the First VLOOKUP formula right after the "With ws"
Dim iRet As Integer
Dim strPrompt As String
Dim strTitle As String
Dim shtName As String
' Prompt
strPrompt = "Please select the last Kronos Full File before the dates of this Report." & vbCrLf & _
"For example, if the date of this report is 9-8-17, you would want to use the closest date Kronos Full File." & vbCrLf & _
"If one was not ran in the past couple days, then run a new Kronos Full File, and then choose that file."
' Dialog's Title
strTitle = "Latest Kronos Full File"
'Display MessageBox
iRet = MsgBox(strPrompt, vbOK, strTitle)
Dim Window2 As String
Dim X As String
Dim lNewBracketLocation As Long
Dim wb2 As Workbook
Window2 = Application.GetOpenFilename( _
FileFilter:="Excel Files (*.xls*),*.xls*", _
Title:="Choose the Newest Kronos Full File", MultiSelect:=False)
Set wb2 = Workbooks.Open(Filename:=Window2, ReadOnly:=True)
shtName = wb2.Worksheets(1).name
wb2.Close
MsgBox "You selected " & Window2
'Find the last instance in the string of the path separator "\"
lNewBracketLocation = InStrRev(Window2, Application.PathSeparator)
'Edit the string to suit the VLOOKUP formula - insert "["
X = Left$(Window2, lNewBracketLocation) & "[" & Right$(Window2, Len(Window2) - lNewBracketLocation)
With ws
.Range("M2").Formula = "=VLOOKUP($K2,'" & X & "]shtName'!$B$2:$E$99999,4,0)"
.Range("N2").Formula = "=VLOOKUP($K2,'" & X & "]shtName'!$B$2:$C$99999,2,0)"
.Range("O2").Formula = "=VLOOKUP($K2,'" & X & "]shtName'!$B$2:$U$99999,20,0)"
.Range("P2").Formula = "=VLOOKUP($K2,'" & X & "]shtName'!$B$2:$Q$99999,16,0)"
.Range("Q2").Formula = "=VLOOKUP($K2,'" & X & "]shtName'!$B$2:$S$99999,18,0)"
End With
Another way to go around using a Range's address from another workbook, is set the range, and later on you can use Range.Address(True, True, xlR1C1, xlExternal). The 4th partameter will add the name of the worksheet and workbook if necessary.
Dim Rng1 As Range ' new Range Object
Window2 = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*),*.xls*", _
Title:="Choose the Newest Kronos Full File", MultiSelect:=False)
Set wb2 = Workbooks.Open(Filename:=Window2, ReadOnly:=True)
'shtName = wb2.Worksheets(1).Name '<-- not necessary
Set Rng1 = wb2.Worksheets(1).Range("B2:E99999")
wb2.Close
With ws
.Range("M2").Formula = "=VLOOKUP($K2," & Rng1.Address(True, True, xlR1C1, xlExternal) & ",4,0)"
' define more ranges for the other formulas
End With
It seems like my issue had to do with the range that I was trying to use the VLOOKUP with. It looks like once I changed the 99999 to only like 9999, then it seemed like the VLOOKUP worked. I am still not sure why but I am pretty sure that was it. I got no error message when I lowered that number range. I am guessing because it was going out of the ranges of the actual worksheet or something.
I am wondering if there is a way to not have to open a workbook to get the information from it. The issue is I am having the user select the file first because the name changes. So I am using Application.GetOpenFilename. Once they select it, since it doesn't actually open, I am trying to just grab some cells from there and copy them over. I have some other cells using vlookups referencing a workbook in the same way but this seems different or won't work. Here is the code:
Dim Window3 As String
Dim x As String
Dim lNewBracketLocation As Long
Dim shtName As String
' Prompt
strPrompt = "Please select the last 'HC Report' located in" & vbCrLf & _
"'C:\file\file\'" & vbCrLf & _
"before the dates of this Report." & vbCrLf & _
"This will be used to find the Interns that are currently working." & vbCrLf & _
"For example, if the date of this report is 9-8-17, you would want to use the 'August 2017.xlsx.' report."
' Dialog's Title
strTitle = "Latest Report"
'Display MessageBox
iRet = MsgBox(strPrompt, vbOK, strTitle)
Window3 = Application.GetOpenFilename( _
FileFilter:="Excel Files (*.xls*),*.xls*", _
Title:="Choose previous quarter's file", MultiSelect:=False)
MsgBox "You selected " & Window3
'below is some extra code from where I used this same startegy for VLOOKUP.
'Not sure if this "x" variable will be needed.
lNewBracketLocation = InStrRev(Window2, Application.PathSeparator)
'Edit the string to suit the VLOOKUP formula - insert "["
x = Left$(Window2, lNewBracketLocation) & "[" & Right$(Window2, Len(Window2) - lNewBracketLocation)
Dim wb3 As Workbook
'I want to do all of this WITHOUT opening this next file. Is that possible?
' If I open this file it works. but I am trying to do it without opening.
'Because it takes a minute
'Set wb3 = Workbooks.Open(Window3)
shtName = wb3.Worksheets("Team Members").name
'*******RIGHT here IS WHERE IT ERRORS******************
'Run-time error '91':
'Object variable or With block variable not set
Stop
wb3.Sheets(shtName).Select
ActiveSheet.Range("$A$1:$P$2769").autofilter Field:=1, Criteria1:="Interns"
Range("A2768").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.COPY
This is some other code I have that takes the vlookup without actually opening the other file. Can I do kind of the same thing? I can't get it to work.
Dim Window2 As String
Dim x As String
Dim lNewBracketLocation As Long
Window2 = Application.GetOpenFilename( _
FileFilter:="Excel Files (*.xls*),*.xls*", _
Title:="Choose previous quarter's file", MultiSelect:=False)
MsgBox "You selected " & Window2
'Find the last instance in the string of the path separator "\"
lNewBracketLocation = InStrRev(Window2, Application.PathSeparator)
'Edit the string to suit the VLOOKUP formula - insert "["
x = Left$(Window2, lNewBracketLocation) & "[" & Right$(Window2, Len(Window2) - lNewBracketLocation)
shtName = ActiveWorkbook.Worksheets(1).name
Stop
MainWindow.Activate
Columns("B:B").Select
Selection.Delete Shift:=xlToLeft
Range("AI2").FormulaR1C1 = "=VLOOKUP(RC2,'" & x & "]shtName'!R3C2:R9694C49, 23, FALSE)"
Range("AJ2").FormulaR1C1 = "=VLOOKUP(RC2,'" & x & "]shtName'!R3C2:R9694C49, 19, FALSE)"
Range("AK2").FormulaR1C1 = "=VLOOKUP(RC2,'" & x & "]shtName'!R3C2:R9694C49, 20, FALSE)"
Range("AL2").FormulaR1C1 = "=VLOOKUP(RC36,'" & x & "]shtName'!R3C2:R9694C49, 23, FALSE)"
It's impossible to copy cells across from a closed workbook. The vlookups are a different story as Excel caches a copy of the result to display when the external workbook is closed.
Just like what you're trying to do, i.e., you need to have the external file opened once to grab the data. With vlookup it's when the formula is typed/pasted into the sheet. At that time the external workbook must either be open or Excel opens it behind the scenes when you select the file from the Update Values:Book1.xlsm file selection dialog. With your code, it's when you want to grab the data. You must open it for you to cache the data yourself.
However you can solve the time issue by using this:
Application.Calculation = xlCalculationManual
Set wb3 = Workbooks.Open(Window3)
and then after you close the workbook, this:
Application.Calculation = xlCalculationAutomatic
I am trying to use some Parsing i was able to tweak a little. If I use it in straight VBA in excel, it works fine. However, when I use the same code as a module in VB.NET I get the error in the title on the line of code
ws.Range(vTitles).AutoFilter()
(duh!) I am not sure what is going wrong in the conversion, since I am not a hardcore VB.Net programmer, so I am doing a lot of googling, but not finding much that works. Any ideas on how this could be fixed or do I have to abandon the idea of using this snippet in VB.Net?
Here is the code I am using:
'turned strict off or autofilter per http://www.pcreview.co.uk/threads/autofilter-method-of-range-class-failed.3994483/
Option Strict Off
Imports xl = Microsoft.Office.Interop.Excel
Module ParseItems
Public Sub ParseItems(ByRef fileName As String)
'Jerry Beaucaire (4/22/2010)
'Based on selected column, data is filtered to individual workbooks are named for the value plus today's date
Dim wb As xl.Workbook
Dim xlApp As xl.Application
Dim LR As Long, Itm As Long, MyCount As Long, vCol As Long
Dim ws As xl.Worksheet, MyArr As Object, vTitles As String, SvPath As String
'Set new application and make wb visible
xlApp = New xl.Application
xlApp.Visible = True
'open workbook
wb = xlApp.Workbooks.Open(fileName)
'Sheet with data in it
ws = wb.Sheets("Original Data")
'Path to save files into, remember the final "\"
SvPath = "G:\MC VBA test\"
'Range where titles are across top of data, as string, data MUST have titles in this row, edit to suit your titles locale
vTitles = "A1:L1"
'Choose column to evaluate from, column A = 1, B = 2, etc.
vCol = xlApp.InputBox("What column to split data by? " & vbLf & vbLf & "(A=1, B=2, C=3, etc)", "Which column?", 1, Type:=1)
If vCol = 0 Then Exit Sub
'Spot bottom row of data
LR = ws.Cells(ws.Rows.Count, vCol).End(xl.XlDirection.xlUp).Row
'Speed up macro execution
'Application.ScreenUpdating = False
'Get a temporary list of unique values from key column
ws.Columns(vCol).AdvancedFilter(Action:=xl.XlFilterAction.xlFilterCopy, CopyToRange:=ws.Range("EE1"), Unique:=True)
'Sort the temporary list
ws.Columns("EE:EE").Sort(Key1:=ws.Range("EE2"), Order1:=xl.XlSortOrder.xlAscending, Header:=xl.XlYesNoGuess.xlYes, _
OrderCustom:=1, MatchCase:=False, Orientation:=xl.Constants.xlTopToBottom, DataOption1:=xl.XlSortDataOption.xlSortNormal)
'Put list into an array for looping (values cannot be the result of formulas, must be constants)
MyArr = xlApp.WorksheetFunction.Transpose(ws.Range("EE2:EE" & ws.Rows.Count).SpecialCells(xl.XlCellType.xlCellTypeConstants))
'clear temporary worksheet list
ws.Range("EE:EE").Clear()
'Turn on the autofilter, one column only is all that is needed
ws.Range(vTitles).AutoFilter()
'Loop through list one value at a time
For Itm = 1 To UBound(MyArr)
ws.Range(vTitles).AutoFilter(Field:=vCol, Criteria1:=MyArr(Itm))
ws.Range("A1:A" & LR).EntireRow.Copy()
xlApp.Workbooks.Add()
ws.Range("A1").PasteSpecial(xl.XlPasteType.xlPasteAll)
ws.Cells.Columns.AutoFit()
MyCount = MyCount + ws.Range("A" & ws.Rows.Count).End(xl.XlDirection.xlUp).Row - 1
xlApp.ActiveWorkbook.SaveAs(SvPath & MyArr(Itm), xl.XlFileFormat.xlWorkbookNormal)
'ActiveWorkbook.SaveAs SvPath & MyArr(Itm) & Format(Date, " MM-DD-YY") & ".xlsx", 51 'use for Excel 2007+
xlApp.ActiveWorkbook.Close(False)
ws.Range(vTitles).AutoFilter(Field:=vCol)
Next Itm
'Cleanup
ws.AutoFilterMode = False
MsgBox("Rows with data: " & (LR - 1) & vbLf & "Rows copied to other sheets: " & MyCount & vbLf & "Hope they match!!")
xlApp.Application.ScreenUpdating = True
End Sub
End Module
Looks like you need to specify at least one optional parameter. Try this:
ws.Range(vTitles).AutoFilter(Field:=1)
I realize this was closed years ago, but I recently ran into this problem and wanted to add to the solution.
This seems to only work when specifically using the first optional Field parameter. I attempted this fix using the optional VisibleDropDown parameter and still got this error.
ws.Range["A1"].AutoFilter(VisibleDropDown: true); Gives error
ws.Range["A1"].AutoFilter(Field: 1); No error
I am quite new in VBA and wrote a subroutine that copy-paste cells from one document into another one. Being more precise, I am working in document 1 where I have names of several product (all in column "A"). For these product, I need to look up certain variables (e.g. sales) in a second document.
The subroutine is doing the job quite nicely, but I want to use it as a funcion, i.e. I want to call the sub by typing in a cell "=functionname(productname)".
I am grateful for any helpful comments!
Best, Andreas
Sub copy_paste_data()
Dim strVerweis As String
Dim Spalte
Dim Zeile
Dim findezelle1 As Range
Dim findezelle2 As Range
Dim Variable
Dim Produkt
'Variable I need to copy from dokument 2
Variable = "frequency"
'Produkt I need to copy data from document 2
Produkt = Cells(ActiveCell.Row, 1)
'path, file and shhet of document 2
Const strPfad = "C:\Users\Desktop\test\"
Const strDatei = "Bezugsdok.xlsx"
Const strBlatt = "post_test"
'open ducument 2
Workbooks.Open strPfad & strDatei
Worksheets(strBlatt).Select
Set findezelle = ActiveSheet.Cells.Find(Variable)
Spalte = Split(findezelle.Address, "$")(1)
Set findezelle2 = ActiveSheet.Cells.Find(Produkt)
Zeile = Split(findezelle2.Address, "$")(2)
'copy cell that I need
strZelle = Spalte & Zeile 'Zelladresse
strVerweis = "'" & strPfad & "[" & strDatei & "]" & strBlatt & "'!" & strZelle
'close document 2
Workbooks(strDatei).Close savechanges:=False
With ActiveCell
.Formula = "=IF(" & strVerweis & "="""",""""," & strVerweis & ")"
.Value = .Value
End With
End Sub
Here is an example to create a function that brings just the first 3 letters of a cell:
Public Function FirstThree(Cell As Range) As String
FirstThree = Left(Cell.Text, 3)
End Function
And using this in a Excel worksheet would be like:
=FirstThree(b1)
If the sub works fine and you just want to make it easier to call you can add a hotkey to execute the Macro. In the developer tab click on Macros then Options. You can then add a shortcut key (Crtl + "the key you want" it can be a shortcut key already used like C, V, S, but you will lose those functions (Copy, Paste Save, Print)
enter image description here
I am a total dummy as for vb and excel, have tried to combine 2 macros that I have found around here, into 1, but obviously did something terribly wrong and now i'm stuck.. First I just used this macro (saved it in as personal.xlsb so as to be able to use it in any workbook)
Sub CSVFile()
Dim SrcRg As Range
Dim CurrRow As Range
Dim CurrCell As Range
Dim CurrTextStr As String
Dim ListSep As String
Dim FName As Variant
FName = Application.GetSaveAsFilename("", "CSV File (*.csv), *.csv")
ListSep = ";"
If Selection.Cells.Count > 1 Then
Set SrcRg = Selection
Else
Set SrcRg = ActiveSheet.UsedRange
End If
Open FName For Output As #1
For Each CurrRow In SrcRg.Rows
CurrTextStr = ìî
For Each CurrCell In CurrRow.Cells
CurrTextStr = CurrTextStr & """" & GetUTF8String(CurrCell.Value) & """" & ListSep
Next
While Right(CurrTextStr, 1) = ListSep
CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1)
Wend
Print #1, CurrTextStr
Next
Close #1
End Sub
That plus the GetUTF8String function code. Now that was working fine. Then I have thought well why not just experiment with my limited (that is a serious understatement) vb understanding, added the following code and changed the CSVFile sub into a function, which I then called from the sub below, with the output file name as a parameter (to be used instead FName = Application.GetSaveAsFilename). I thought yeah, this code saves all sheets automatically, now let's just make sure that the encoding and delimiter/enclosure setting function runs before each sheet is saved. It doesn't seem right but I thought hey why not try..
Public Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven
' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
' Save the file in current director
OutputPath = ThisWorkbook.Path
If OutputPath <> "" Then
Application.Calculation = xlCalculationManual
' save for each sheet
For Each Sheet In Sheets
OutputFile = OutputPath & Application.PathSeparator & Sheet.Name & ".csv"
' make a copy to create a new book with this sheet
' otherwise you will always only get the first sheet
Sheet.Copy
' this copy will now become active
CSVFile(OutputFile)
ActiveWorkbook.SaveAs Filename:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Close
Next
Application.Calculation = xlCalculationAutomatic
End If
Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
Exit Sub
Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
"Source: " & Err.Source & " " & vbCrLf & _
"Number: " & Err.Number & " " & vbCrLf & _
"Description: " & Err.Description & " " & vbCrLf
GoTo Finally
End Sub
Saved that and with that I have managed to achieve something very different. On opening any workbooks, that macro runs and opens up my sheets from that particular workbook as csv files (without saving them). Now I am like Alice in Wonderland. How come it is running on file open? That is not desirable, so I went back to the macro code and changed it back to just the csvfile sub. Well that didn't help, no idea what I did there, was definitely editing the same macro... So I deleted the macro, the modul, I cannot imagine where the thing now is but it's still running + I get this warning that macros were deactivated. Can't get rid of it! Now lads, I'm sorry for the total lack of professionality from my side, this was just supposed to be a small favor for a client, without wasting loads of time learning vb, coz my boss doesn't like that... I am of course interested in how to achieve the goal of saving the sheets automatically after setting the deimiter and enclosure in them. And at this moment I am very interested in how to get rid of that macro and where it is hiding.. What have I done?! Thank you for your patience!
I think the problem lies with the line
OutputPath = ThisWorkbook.Path
Because you are running this from your personal.xlsb which is stored in your XLSTART folder it has created the CSV files in the same location. When Excel starts it will try and load any files that it finds in that location.
Just locate your XLSTART folder and delete any CSV files you find there.
Try using
OutputPath = ActiveWorkbook.Path
XLSTART folder location, dependent on your system, is probably something like:
C:\Users\YOURNAME\AppData\Roaming\Microsoft\Excel\XLSTART