Taking info from closed workbook that has variable name - vba

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

Related

VLOOKUP works with FormulaR1C1 but not Regular Formula?

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)

Error 1004 application-defined or object-defined error using vlookup?

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.

VBA to copy specific sheet to existing book

The task here is two fold (the first part already works though).
Task 1: Copy a sheet that's been selected from a combo box into a new document.
Task 2: Copy a specific sheet from the original document and add it to the new document that was created above.
So far I've got this: (but the second task doesn't work)
Sub Extract()
Dim wbkOriginal As Workbook
Set wbkOriginal = ActiveWorkbook
'sets site and engineer details into the estate page that is being extracted
Worksheets(FrontPage.CmbSheet.Value).Range("B3").Value = Worksheets("front page").Range("E6")
Worksheets(FrontPage.CmbSheet.Value).Range("D3").Value = Worksheets("front page").Range("N6")
Worksheets(FrontPage.CmbSheet.Value).Range("F3").Value = Worksheets("front page").Range("K6")
Worksheets(FrontPage.CmbSheet.Value).Range("B4").Value = Worksheets("front page").Range("F8")
Worksheets(FrontPage.CmbSheet.Value).Range("D4").Value = Worksheets("front page").Range("K8")
' copies sheet name from combo box into new document, saves it with site name and current date
' into C:\Temp\ folder for ease of access
With ActiveWorkbook.Sheets(FrontPage.CmbSheet.Value)
.Copy
ActiveWorkbook.SaveAs _
"C:\temp\" _
& .Cells(3, 2).Text _
& " " _
& Format(Now(), "DD-MM-YY") _
& ".xlsm", _
xlOpenXMLWorkbookMacroEnabled, , , , False
End With
Dim wbkExtracted As Workbook
Set wbkExtracted = ActiveWorkbook
Workbooks(wbkOriginal.Name).Sheets(DOCUMENTS).Copy _
After:=Workbooks(wbkExtracted.Name).Sheets(wbkExtracted.Name).Sheets.Count
'code to close the original workbook to prevent accidental changes etc
'Application.DisplayAlerts = False
'wbkOriginal.Close
'Application.DisplayAlerts = True
End Sub
I'm hoping one of you clever folks out there can tell me what I'm doing wrong :)
I think I know the problem you are running into. (Maybe) If you are working with a new instance of excel you need to save it then reopen it. It must have something to do with the object model. I had to do this not too long ago. Here is a snippet of the code I used.
Set appXL = New Excel.application
appXL.Workbooks.Add
Set wbThat = appXL.ActiveWorkbook
wbThat.application.DisplayAlerts = False
wbThat.SaveAs Filename:=strFilePath & "\" & strFileName
'This code needed to allow the copy function to work
wbThat.Close savechanges:=True
Set wbThat = Nothing
Set wbThat = application.Workbooks.Open(strFilePath & "\" & strFileName)
appXL.Quit
Set appXL = Nothing
'Copy Help page from this workbook to the report
wbThis.Sheets("Help").Copy after:=wbThat.Sheets(wbThat.Sheets.Count)
Sub Full_Extract()
Dim wbkOriginal As Workbook
Set wbkOriginal = ActiveWorkbook
'sets site and engineer details into the estate page that is being extracted
Worksheets(Sheet1.CmbSheet.Value).Range("B3").Value = Worksheets("front page").Range("E6")
Worksheets(Sheet1.CmbSheet.Value).Range("D3").Value = Worksheets("front page").Range("N6")
Worksheets(Sheet1.CmbSheet.Value).Range("F3").Value = Worksheets("front page").Range("K6")
Worksheets(Sheet1.CmbSheet.Value).Range("B4").Value = Worksheets("front page").Range("F8")
Worksheets(Sheet1.CmbSheet.Value).Range("D4").Value = Worksheets("front page").Range("K8")
' copies sheet name from combo box into new document, saves it with site name and current date
' into C:\Temp\ folder for ease of access
With ActiveWorkbook.Sheets(Array((Sheet1.CmbSheet.Value), "Z-MISC"))
.Copy
ActiveWorkbook.SaveAs _
"C:\temp\" _
& ActiveWorkbook.Sheets(Sheet1.CmbSheet.Value).Cells(3, 2).Text _
& " " _
& Format(Now(), "DD-MM-YY") _
& ".xlsm", _
xlOpenXMLWorkbookMacroEnabled, , , , False
End With
'code to close the original workbook to prevent accidental changes etc
Application.DisplayAlerts = False
wbkOriginal.Close
Application.DisplayAlerts = True
End Sub

Excel VBA: Formula Not Entering Correctly From String

I'm trying to finish a script that will allow a user to select another excel file when a cell is double clicked, then that excel file is used to drop in a formula into the main excel file.
I cannot use the cell values alone because being able to see the file path in the formula bar when the script is complete is required. So the issue is that the formula being entered does not match the string text that it should be pulling from.
For clarification, the string I use called FormulaPath ends up being a formula ending "...\00975-006-00[00975-006-00.xls]QuoteDetails'!" and this would be the correct formula.
But when I use this to enter the formula into a range:
Range("A1").Formula = "=" & FormulaPath & "$C$100"
The actual formula ends up being entered as "...[00975-006-00[00975-006-00.xls]Quote Details]00975-006-00[00975-006-00.xls]Q'!$C$100
Notice the repetition?
I'm on mobile right now, so forgive me if the formatting is wacky. Full script below. Thanks!
Option Explicit
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim ImportWB, QuoteWB As Workbook
Dim AdInsWS, AdInsCostWS As Worksheet
Dim ImportPathName As Variant
Dim FormulaPath As String
Set QuoteWB = ThisWorkbook
Set AdInsWS = QuoteWB.Sheets("Ad-Ins")
Set AdInsCostWS = QuoteWB.Sheets("Ad-ins cost")
If Not Intersect(Target, Range("B:B")) Is Nothing Then
'set default directory
ChDrive "Y:"
ChDir "Y:\Engineering Management\Manufacturing Sheet Metal\Quotes"
'open workbook selection
ImportPathName = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*), *.xls*", Title:="Please select a file")
If ImportPathName = False Then 'if no workbook selected
MsgBox "No file selected."
ElseIf ImportPathName = ThisWorkbook.Path & "\" & ThisWorkbook.Name Then 'if quote builder workbook selected
MsgBox "Current quote workbook selected, cannot open."
Else
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Workbooks.Open Filename:=ImportPathName, UpdateLinks:=False
Set ImportWB = ActiveWorkbook
FormulaPath = "'" & ImportWB.Path & "[" & ImportWB.Name & "]Quote Details'!"
AdInsCostWS.Range("B3").Formula = "=" & FormulaPath & "$C$100"
ImportWB.Close
End If
Cancel = True
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End If
End Sub
I got your script to work by simply adding a backslash to the FormulaPath string:
FormulaPath = "'" & ImportWB.Path & "\[" & ImportWB.Name & "]Quote Details'!"
ImportWB.Path is importing the Path with the excel name, split the path string

excel macro save sheets as csv with specific delimiter and enclosure

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