How Do I Resolve Run-Time Error With GetValue Function in Excel VBA? - vba

I am trying to write a macro that copies data from multiple external workbooks to a single workbook in a certain order. I do not intend to have each workbook be open for my macro to work, as that would be an outrageous number of open spreadsheets, so I did a Google search and came across this nifty function, the GetValue function:
http://spreadsheetpage.com/index.php/tip/a_vba_function_to_get_a_value_from_a_closed_file/
Just to set myself up for the rest of the code, I made a code that is supposed to simply take a single piece of data from a cell of an external workbook, and put it in a single cell of the workbook and sheet I'm currently in. In the current worksheet, I stuck the file paths of the workbooks I want access into the B column, and the file names in the A column, since there are so many and I want to be able to access each in a single code. Here is that code:
Sub Gather_Data()
Dim p As String
Dim f As String
Dim s As String
Dim a As String
p = Range("B7").Value
f = Range("A7").Value
s = Sheet5
a = D7
Cells(10, 10).Value = GetValue(p, f, s, a).Value
End Sub
Private Function GetValue(path, file, sheet, ref)
' Retrieves a value from a closed workbook
Dim arg As String
' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
' Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
End Function
I don't see anything wrong with the code, but whenever I try to run it I get a run-time error that states, "Method 'Range' of object '_Global' failed". I honestly have no idea what that means and running the debugger highlights the
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
area, which I didn't even write. If anyone has experience using this function or knows how to resolve this error, your input would be greatly appreciated. Thanks in advance!

Your variables are declared as String, so try changing your code from this:
s = Sheet5
a = D7
To this:
s = "Sheet5"
a = "D7"

Related

Excel VBA: Can't create sheets on called another Excel file

The goal is to open another Excel file with parameters from first / main file and call macro who creates 1 or n new sheets with data from database, but Excel won't create new sheets in second file and then all other logic fails.
You can find sample code for two files below. When B file is opened manually and called tst() sub, this works, but not when first file opens second file. Workbooks are not protected, I'm using MS Excel 2010.
A_file.xlsm is main file where user calls GetFile to open another file and run ReadParams macro. Code is located in modules.
Sub GetFile(fileName As String)
Dim filePath, par1, par2, currentUser As String
Dim targetFile As Workbook
currentUser = CreateObject("WScript.Network").UserName
filePath = "C:\Users\" & currentUser & "\Documents\Excel_APPS\"
par1 = "USE_R_one"
par2 = "some_val"
Application.ScreenUpdating = False
Set targetFile = Workbooks.Open(filePath & "B_file.xlsm")
Application.Run "'" & targetFile.Name & "'!ReadParams(" & Chr(34) & par1 & Chr(34) & ", " & Chr(34) & par2 & Chr(34) & ")"
targetFile.Activate
Application.ScreenUpdating = True
End Sub
B_file.xlsm macros:
Sub ReadParams(s_uno As String, s_duo As String)
If IsNull(s_uno) Or IsNull(s_duo) Then
MsgBox "Error occurred.", vbExclamation, "Error"
Else
MsgBox "All params are ok, new sheet is coming right after this msg"
ThisWorkbook.Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "Sheet_Data" '<-- THIS WON'T WORK
End If
End Sub
Sub tst()
ReadParams "USE_R", "test"
End Sub
The problem is in the line Application.Run...
The syntax for this is
Application.Run "'b.xlsm'!ReadParams", par1, par2
You had your parameters concatenated to the first argument

How to copy data from closed workbook into a master workbook

I need help copying data from a closed workbooks (without opening them) into a column in the master workbook using VBA. I keep getting the error:
Run-time Error 424: object required
Here is my code:
Set x = Workbooks.Open("C:\Users\DD\Desktop\EMS")
x.Sheets("PO Report").Range("Y3:Y500").Copy
y.Activate
Sheets("Sheet1").Range("Q2").PasteSpecial
Application.CutCopyMode = False
x.Close
Thanks for the help in advance!
this is the problem - you are not specifying the filename of the excel file
Set x = Workbooks.Open("C:\Users\DD\Desktop\EMS")
you cannot read data out of a closed file... it has to be open
you also need to Dim your x object
Dim x as object
I altered the code posted here. Insert the following code in your "Sheet1" sheet module:
Option Explicit
Sub GetDataDemo()
Dim FilePath$
Dim i As Long
Const FileName$ = "EMS.xlsx"
Const SheetName$ = "PO Report"
FilePath = "C:\Users\DD\Desktop\"
DoEvents
Application.ScreenUpdating = False
If Dir(FilePath & FileName) = Empty Then
MsgBox "The file " & FileName & " was not found", , "File Doesn't Exist"
Exit Sub
End If
For i = 3 To 500
Range("Q" & i - 1) = GetData(FilePath, FileName, SheetName, Range("Y" & i))
Next i
ActiveWindow.DisplayZeros = False
End Sub
Private Function GetData(Path, File, Sheet, Rng)
Dim Data$
Data = "'" & Path & "[" & File & "]" & Sheet & "'!" & Rng.Address(, , xlR1C1)
GetData = ExecuteExcel4Macro(Data)
End Function

Index() & Indirect() on a closed Excel

I have a few closed Excel workbooks, which I would be willing to access with =INDEX(MATCH) without openning them.
Unfortunately, I want to refer to them indirectly, thus based on the current sheet I am in.
E.g. - if I am in sheet -> then file path:
AAB -> 'C:\Users\vityata\Desktop\[AAB]Test'!$A:E
BBC -> 'C:\Users\vityata\Desktop\[BBC]Test'!$A:E
It seems like a trivial task, but the only options to do something like this seem to be the following:
Open the sheet and then use Indirect() (but I do not want to open the sheet)
Use VBA code (but it should be somehow reusable and really last resort)
Use data connection (I do not want it)
Use INDIRECT.EXT (but I do not want 3. party add-ins)
I have checked similar problems here: How to referencing value in closed excel workbook by formula incl. variable sheetname? but the first solution is rather too colmplicated to do it.
Any new ideas or best practices?
Update
So far I have achieved the following with VBA (although I would love to have a non-VBA solution):
Option Explicit
Public Sub VlookupClosedWb(Optional strLookFor As String = "Erteilung Baugenehmigung", _
Optional strSheet As String = "APF", _
Optional lngColIndex As Long = 2)
Dim strRange As String
strRange = "'" & ThisWorkbook.Path & "\[" & strSheet & ".xlsx]" & "Monatsbericht'!$A:$E"
ActiveCell.Formula = "=VLOOKUP(""" & strLookFor & """," & strRange & "," & lngColIndex & ",0)"
End Sub
Public Function fVlookupClosedWb(Optional strLookFor As String = "Erteilung Baugenehmigung", _
Optional strSheet As String = "APF", _
Optional lngColIndex As Long = 2)
Dim strRange As String
strRange = "'" & ThisWorkbook.Path & "\[" & strSheet & ".xlsx]" & "Monatsbericht'!$A:$E"
fVlookupClosedWb = WorksheetFunction.VLookup(""" & strLookFor & """, " & strRange & ", " & lngColIndex & ", 0)
End Function
Long story short - the Sub works as expected, providing exactly what I want in the active cell. The Function does not work. Any ideas how to make it work? I suppose that it does not work, because I am abusing a bit WorksheetFunction.VLookup, but I cannot pass a range without openning the other workbook. Ideas?
After some tries, I found out that the way to use some formulas on a closed excel workbook, without referring to the path is by using the Sumproduct() function.
E.g.:
If you want to use Sumproduct() as an alternative of Sumifs() this is how it looks like with two conditions:
=SUMPRODUCT(((B2:B6=C2)*1)*(A2:A6=D2))
*SUMPRODUCT(((B8:B13=C8)*1)*(A8:A13=D8))
*SUMPRODUCT(((B16:B20=C16)*1)*(A16:A20=D16))
I have put some more examples of it here.

"Error 2023" with "ExecuteExcel4Macro" when fetching a value

I maintain an Excel-workbook with VBA in it.
The VBA fails when fetching a value from a closed Excel-workbook with "ExecuteExcel4Macro".
The workbook to fetch the value from is kept on an intranet-webpage.
GetValue = ExecuteExcel4Macro(arg)
This line of code fails. "Error 2023" is returned.
By tinkering with the code I discovered:
tmp = GetValue(path, file, sheet, ref)
' tmp gets the "Error 2023"-return.
Debug.Print tmp
' Gets the expected data-value from the excel-sheet.
Datum_Homepage = GetValue(path, file, sheet, ref)
If you call it two times the first call gets the "Error 2023" and the second call gets the expected value (a date).
How is that possible?
The complete code of the GetValue-function:
Public Function GetValue(path, file, sheet, ref) As Variant
Dim arg As String
If Right(path, 1) <> "/" Then path = path & "/"
arg = "'" & path & "[" & file & "]" & sheet & "'!" & Range(ref).Address(, , xlR1C1)
GetValue = ExecuteExcel4Macro(arg)
End Function

Export As A Fixed Format Excel 2007

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.