Getting ExecuteExcel4Macro to Recognise Empty Cells - excel

When I use the ExecuteExcel4Macro function in a VBA script like so:
Public Function GetNamedData(Path, File, Address)
Dim Data As String
Data = "'" & Path & File & "'!" & Address
GetNamedData = ExecuteExcel4Macro(Data)
End Function
Where Address is a named range in my case, if the cell in the closed workbook is empty, this function returns 0. But some cells contain (deliberately) 0.
How do I differentiate between empty cells and cells containing 0?
To explain further, I am using this function to get data from a closed workbook. This has proven very fast at collecting lots of data from closed workbooks.
I understand there are differences between '0' and empty, but I am not sure how to work it into this function.

Try this one:
GetNamedData = ExecuteExcel4Macro("IF(COUNTA(" & Data & ")," & Data & ",""X"")")
Then GetNamedData = "X" in case the cell in closed workbook is empty.

The below function adds a "" (Null) the the value and so the GetValue2 function returns a null if empty or a zero if it is a zero.
Function GetValue2(strPath As String, strFilename As String, strTabName As String, intColumnNumber As Integer, intRowNumber As Integer) As String
Dim varCellValue As Variant
Dim strContents As String
On Error GoTo ErrHandler
varCellValue = ExecuteExcel4Macro("'" & strPath & "[" & strFilename & "]" & strTabName & "'!R" & intRowNumber & "C" & intColumnNumber & " & """"")
strContents = CStr(varCellValue)
GoTo NiceExit
ErrHandler:
Call MsgBox("strPathFilename : " & strPath & strFilename & Chr(13) & _
"strTabName : " & strTabName & Chr(13) & _
"intColumnNumber : " & intColumnNumber & Chr(13) & _
"") ' & Error.msg, vbOKOnly)
NiceExit:
GetValue2 = strContents
End Function

Related

VBA custom function works when called in a subroutine but gives value error when entered in a cell

code:
Function getValue(pathname, filename, sheet, rng)
If Right(path, 1) <> ":" Then path = path & ":"
Dim rngR1C1, ref As String:
rngR1C1 = Range(rng).Address(, , xlR1C1)
ref = "'" & pathname & "[" & filename & "]" & sheet & "'!" & rngR1C1
getValue = ExecuteExcel4Macro(ref)
End Function

Run-Time Error 1004 When Using Vlookup with ExecuteExcel4Macro

How do you properly construct a VLOOKUP statement in Excel VBA when using the ExecuteExcel4Macro function in VBA?
I have a function that successfully looks up a value in another excel workbook without opening it using ExecuteExcel4Macro, but when I attempt to change the statement to a VLOOKUP statement I get a Run-time error 1004:
The function:
Public Function fGetValueTest(sFilePath, sFileName, sSourceSheet, sSourceCell, vVal, Col)
'Returns the value of a cell from a closed file [BD]
'Declaring variables [BD]
Dim sStringMacro As String
Dim externalValue As Variant
'Setting variables [BD]
externalValue = ExecuteExcel4Macro("'" & sFilePath & "[" & sFileName & "]" & sSourceSheet & "'!" & _
Range("A1").Range(sSourceCell).Address(, , xlR1C1))
'Exception error on file not found [BD]
If Dir(sFilePath & sFileName) = "" Then
fGetValueTest = "File Not Found!"
Exit Function
End If
'If value of source cell is N/A [BD]:
If Application.IsNA(externalValue) Then
'Skip and move on [BD]
fGetValueTest = "0"
ElseIf IsError(externalValue) Then
MsgBox "Error - Check fGetValue Function"
Else
'Creating macro variable [BD]
sStringMacro = "'" & sFilePath & "[" & sFileName & "]" & sSourceSheet & "'!" & _
Range("A1").Range(sSourceCell).Address(, , xlR1C1)
fGetValueTest = ExecuteExcel4Macro("Vlookup(" & vVal & "," & sStringMacro & "," & Col & ",0)")
End If
End Function
And it's usage in the subroutine:
Sub TestGetValue()
Dim sFileName As String
Dim sFilePath As String
Dim sSourceSheet As String
Dim sSourceCell As String
Dim sDestinationCell As String
Dim sDestinationSheet As String
Dim vVal As String
Dim Col As String
sFileName = "0306-0312 Margin Master.xlsx"
sFilePath = "\\store\GroupDrives\Pricing\_Deli_\Deli Fresh Shift\Margin Master\"
sSourceSheet = "Bakery"
sDestinationSheet = "TestSheet"
sSourceCell = "G10"
sDestinationCell = "G10"
vVal = "A10"
Col = 3
ThisWorkbook.Worksheets(sDestinationSheet).Range(sDestinationCell) = fGetValueTest(sFilePath, sFileName, sSourceSheet, sSourceCell, vVal, Col)
End Sub
I don't see any errors in how the VLOOKUP statement is constructed, does ExecuteExcel4Macro require a different type of statement or is there something else going on here?
Any help would be greatly appreciated, and if anyone happens to know if there is a manual for ExecuteExcel4Macro or any documentation of any real value that would also be helpful!
This is a possibility if it can be adopted:
Function:
Public Function GetVlookup(path, file, sheet, ref, Col, vVal)
' 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
GetVlookup = "File Not Found"
Exit Function
End If
If IsNumeric(vVal) Then
vVal = CDbl(vVal)
Else
vVal = Chr(34) & vVal & Chr(34)
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Address(, , xlR1C1)
' Execute an XLM macro
GetVlookup = ExecuteExcel4Macro("Vlookup(" & vVal & "," _
& arg & "," & Col & ",0)")
End Function
Subroutine:
Sub TestThingSub()
Dim Varr As Variant
Varr = GetVlookup("\\store\GroupDrives\Pricing\_Deli_\Deli Fresh Shift\Margin Master\", "0306-0312 Margin Master2.xlsx", "Sheet2", "A1:B26", 2, "HORSE")
MsgBox Varr
End Sub

Error assigning string to object

I'm trying to search for a file, in d:\ folder with the name Division_Application_Partner.xlsx where Division Application and Partner are variables holding string values.
This is the code I gave:
Set WorkbookPath = Dir(path & Division + "_" + Application + "_" + TradingPartner + ".xlsx")`enter code here`
It throws an error saying " Compile Error: Type Mismtach "
Is the name of the file im giving wrong
Here's the code:
Dim WorkbookPath As WorkBook
Dim path as String
Division = Range("C11").Value
Application = Range("C15").Value
TradingPartner = Range("C19").Value
path = "d:\"
'MsgBox (path)
'MsgBox (Division)
'MsgBox (Application)
MsgBox (TradingPartner)
If Len(Dir(path & Division & "_" & Application & "_" & TradingPartner & ".xlsx")) = 0 Then
Set WorkbookPath = Division & "_" & Application & "_" & TradingPartner & ".xlsx"
End If
I tried concatenating using & like you suggested. Still it shows the same error.
You try assign string to object, this why you getting an error
Dim WorkbookPath As WorkBook
Better try
Dim myWkb as Workbook
Set myWkb = Workbooks.Open(your_concat_string)
and dont use reserved words
Application
Finally
Sub test()
Dim wkbExternWorkbook As Workbook
Dim strPath As String
Dim strDivision As String, strApplication As String, strTradingPartner As String
strDivision = Range("C11").Value
strApplication = Range("C15").Value
strTradingPartner = Range("C19").Value
strPath = "D:\"
If Len(Dir(strPath & strDivision & "_" & strApplication & "_" & strTradingPartner & ".xlsx")) <> 0 Then
Set wkbExternWorkbook = Workbooks.Open(strPath & strDivision & "_" & strApplication & "_" & strTradingPartner & ".xlsx")
End If
End Sub
I would start with using & exclusively for string concatenation. The use of + is primarily for adding numbers though it can concatenate strings. However, there are all sorts of caveats to that when using option strict and so forth, so you're better off using what was intended.
The other thing you should do is actually output all those variables before attempting to concatenate or pass them to Dir. Something like:
MsgBox "[" & path & "]"
repeated for all the others as well. The output of that may well point to the problem.
Try this:
Sub test()
Dim application As Variant
Dim division As Variant
Dim WorkbookPath As String
Dim tradingpartner As Variant
Dim path As String
division = Range("C11").Value
application = Range("C15").Value
tradingpartner = Range("C19").Value
path = "d:\"
'MsgBox (path)
'MsgBox (Division)
'MsgBox (Application)
MsgBox (tradingpartner)
If Len(Dir(path & division & "_" & application & "_" & tradingpartner & ".xlsx")) = 0 Then
Workbooks.Add
ActiveWorkbook.SaveAs division & "_" & application & "_" & tradingpartner & ".xlsx"
End If
End Sub
You would first add the workbook and then save it using the created name.

sumproduct Formula array in VBA

ActiveSheet.Evaluate("=SUMPRODUCT((""" & Source1_Val & """ = " & Target1 & ")*(""" & Source2_Val & """ = " & target2 & ")*ROW(" & Target1 & "))")
The same formula works when I directly put in Excel but when done throught VBA I am not getting any result.
Excel formula:
=SUMPRODUCT((Source!Q2=Q1:Q33)*(Source!L2 = L1:L33)*ROW(L1:L33))
Are you looking for MSDN -Using Ranges?
Range("AD:AD").Select
Range("AE:AE").Select
Are Column1, etc., all defined names? Then:
.Evaluate("=SUMPRODUCT((Column1=Source1_Val)*(Column2=Source2_Val)*ROW())")
The answer is pretty dumb. Remove the = sign from the text.
Assume that the cell D7:D9 as well as E7:E9 contains numeric values, the following function works well in the immediate window
?Evaluate("SUMPRODUCT(D7:D9, E7:E9)")
EDIT: With the assumption that all the variables names below are string.
dim myFormula as string
myFormula = "SUMPRODUCT((" & Source1_Val & " = " & Target1 & ")" _
& " * (" & Source2_Val _
& " = " & target2 & ")*ROW(" & Target1 & "))"
ActiveSheet.Evaluate(myFormula)
There is no need to include extra double-quotes in the formula.
EDIT2: Based on the attached file, here is the code to show that it works
option explicit
Sub TestFormulaStringUsingEvaluate()
Dim formula As String
Dim source1_Val As String
Dim source2_Val As String
Dim target1 As String
Dim target2 As String
'** Fill in the values for the following 4 variables
source1_Val = "Source!Q2"
target1 = "Target!Q$1:Q$10"
source2_Val = "Source!L2"
target2 = "Target!L$1:L$10"
formula = "SUMPRODUCT((" & source1_Val & "= " & target1 & ") " _
& "*(" & source2_Val & "=" & target2 & ") " _
& "* ROW(" & target2 & "))"
MsgBox Application.Evaluate(formula)
End Sub

ExecuteExcel4Macro to get value from closed workbook

I found this bit of code and thought it might be good to use if I just need to pull one value from a closed sheet.
strInfoCell = "'" & strPath & "[" & strFile & "]Sheet1'!R3C3"
myvalue = ExecuteExcel4Macro(strInfoCell)
When I run this code I get a value for strinfocell of
'C:\Users\my.name\Desktop[QOS DGL stuff.xlsx]Sheet1'!R3C3
But when I run the code a dialogue pops up, showing desktop files with "QOS DGL suff" showing.
What's causing this, why is it not just pulling back the data as expected?
I know the path and file name are right, because if I copy them from the debug output and paste them in to start>>run then the correct sheet opens.
I know that Sheet1 (named: ACL), does have a value in cells(3,3)
It depends on how you use it. The open file dialog box is being showed to you because the "strPath" doesn't have a "" in the end ;)
Try this code.
Option Explicit
Sub Sample()
Dim wbPath As String, wbName As String
Dim wsName As String, cellRef As String
Dim Ret As String
'wbPath = "C:\Documents and Settings\Siddharth Rout\Desktop\"
wbPath = "C:\Users\my.name\Desktop\"
wbName = "QOS DGL stuff.xls"
wsName = "ACL"
cellRef = "C3"
Ret = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, -4150)
MsgBox ExecuteExcel4Macro(Ret)
End Sub
Similar application, but no hard coded paths as in the examples above. This function copies the value from another closed workbook, similar to the =INDIRECT() function, but not as sophisticated. This only returns the value...not a reference..so it cannot be used with further functions which require references (i.e.: VLOOKUP()). Paste this code into a new VBA module:
'Requires filename, sheetname as first argument and cell reference as second argument
'Usage: type in an excel cell -> =getvalue(A1,B1)
'Example of A1 -> C:\TEMP\[FILE1.XLS]SHEET1'
'Example of B1 -> B3
'This will fetch contents of cell (B3) located in (sheet1) of (c:\temp\file1.xls)
'Create a module and paste the code into the module (e.g. Module1, Module2)
Public xlapp As Object
Public Function getvalue(ByVal filename As String, ref As String) As Variant
' Retrieves a value from a closed workbook
Dim arg As String
Dim path As String
Dim file As String
filename = Trim(filename)
path = Mid(filename, 1, InStrRev(filename, "\"))
file = Mid(filename, InStr(1, filename, "[") + 1, InStr(1, filename, "]") - InStr(1, filename, "[") - 1)
If Dir(path & file) = "" Then
getvalue = "File Not Found"
Exit Function
End If
If xlapp Is Nothing Then
'Object must be created only once and not at each function call
Set xlapp = CreateObject("Excel.application")
End If
' Create the argument
arg = "'" & filename & "'!" & Range(ref).Range("A1").Address(, , xlR1C1)
'Execute an XLM macro
getvalue = xlapp.ExecuteExcel4Macro(arg)
End Function
Code above
strInfoCell = "'" & strPath & "[" & strFile & "]Sheet1'!R3C3"
myvalue = ExecuteExcel4Macro(strInfoCell)
Should read
strInfoCell = "'" & strPath & "[" & strFile & "]" & "Sheet1'!R3C3"
myvalue = ExecuteExcel4Macro(strInfoCell)
It is missing " & "
No need for a function
Cheers
Neil
Data = "'" & GetDirectory & "[" & GetFileName & "]" & Sheet & "'!" & Range(Address).Range("A1").Address(, , xlR1C1)
Address = "$C$3"
GetDirectory = "C:\Users\my.name\Desktop\"
GetFileName = "QOS DGL stuff.xlsx"
Sheet = "ACL"

Resources