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"
Related
This question already has answers here:
Open Excel file for reading with VBA without display
(10 answers)
Closed 5 years ago.
Set ObjWB = Workbooks.Open("c:\Test.xlsx")
If I used workbooks.open command, that Excel workbook opens.
I need without open that Excel workbook to read the cell value.
Run the Sub GetValue after setting the parameters in ReadFromClosedWorkbook (Workbook & Worksheet). You could pass either or both of them as arguments from the calling procedure.
Sub GetValue()
Debug.Print ReadFromClosedWorkbook("A1")
End Sub
Private Function ReadFromClosedWorkbook(Target As String) As Variant
Const WbFullName = "D:\My Documents\Your file name.xlsx"
Dim PathName As String
Dim WbName As String
Dim WsName As String
Dim Target As String
Dim Sp() As String
WsName = "My Worksheet's Name"
Sp = Split(WbFullName, "\")
WbName = Sp(UBound(Sp))
ReDim Preserve Sp(UBound(Sp) - 1)
PathName = Join(Sp, "\") & "\"
If Len(Dir(WbFullName)) Then
Target = "'" & PathName & _
"[" & WbName & "]" & WsName & _
"'!" & Range(Target).Address(True, True, xlR1C1)
ReadFromClosedWorkbook = ExecuteExcel4Macro(Target)
End If
End Function
I'm trying to test if a cell in a closed external workbook is N/A. In the code below, cell "G5" in the referenced workbook is definitely N/A, but when referencing it using the IsNA function below it returns "Good to go!" when the intention is for it to return "Hay!" in the message box.
Sub TestTest()
'Declaring variables [BD]
Dim sFilePath As String
Dim sFileName As String
Dim sSourceSheet As String
Dim sSourceCell As String
sFileName = "0306-0312 Margin Master.xlsx"
sFilePath = "\\store\GroupDrives\Pricing\_Deli_\Deli Fresh Shift\Margin Master\"
sSourceSheet = "Bakery"
sSourceCell = "G5"
If Application.WorksheetFunction.IsNA("'" & sFilePath & "[" & sFileName & "]" & sSourceSheet & "'!" & _
Range("A1").Range(sSourceCell).Address(, , xlR1C1)) Then
MsgBox "Hay!"
Else
MsgBox "Good to go!"
End If
End Sub
Try using ExecuteExcel4Macro:
Sub TestTest()
'Declaring variables [BD]
Dim sFilePath As String
Dim sFileName As String
Dim sSourceSheet As String
Dim sSourceCell As String
dim externalValue As Variant
sFileName = "0306-0312 Margin Master.xlsx"
sFilePath = "\\store\GroupDrives\Pricing\_Deli_\Deli Fresh Shift\Margin Master\"
sSourceSheet = "Bakery"
sSourceCell = "G5"
externalValue = ExecuteExcel4Macro("'" & sFilePath & "[" & sFileName & "]" & sSourceSheet & "'!" & _
Range("A1").Range(sSourceCell).Address(, , xlR1C1))
If Application.IsNa(externalValue) Then
MsgBox "Hay!"
ElseIf IsError(externalValue) Then
MsgBox "May not work"
Else
MsgBox "Good to go! (value is '" & externalValue & "')"
End If
End Sub
Note: Range("A1").Range(sSourceCell).Address(, , xlR1C1) can probably be abbreviated to Range(sSourceCell).Address(, , xlR1C1) if you are just using cell references such as "G5" as the values of sSourceCell.
An alternative may be to use Evaluate() with a "regular formula", i.e.
Sub TestTest()
'Declaring variables [BD]
Dim sFilePath As String, sFileName As String, sSourceSheet As String, sSourceCell As String
sFileName = "0306-0312 Margin Master.xlsx"
sFilePath = "\\store\GroupDrives\Pricing\_Deli_\Deli Fresh Shift\Margin Master\"
sSourceSheet = "Bakery"
sSourceCell = "R5C7"
If Application.WorksheetFunction.IsError(Evaluate("=('" & sFilePath & "[" & sFileName & "]" & sSourceSheet & "'!" & sSourceCell & ")")) Then
MsgBox "Hay!"
Else
MsgBox "Good to go!"
End If
End Sub
It should work for you if the cell is truly an #N/A error. If it's just a string that's #N/A, you can just tweak that If statement to check evaluate the cell value.
Note: The Cell Reference needs to be R1C1 style, I believe.
I have a module function in this report that concatenates certain cells:
Function AnalysisResults(Specs As Range, Results As Range)
AnalysisResults = Join(Specs) & ";" & Replace(Join(Results), ",", ".")
End Function
Private Function Join(Range As Range, Optional ByRef Delimeter As String = " ")
Dim Str As String
For Each cell In Range
If Str <> "" Then Str = Str & Delimeter
Str = Str & cell.Value
Next
Join = Str
End Function
Then i have a command button that save my file as CSV. It works, but the where the function cells are the value saved is #NAME?.
If I Save As manually as CSV comma delimited, it saves correctly and the formula values appears.
Here is the code of the CommandButton:
Dim myValue As Variant
myValue = InputBox("Specifica numele WBT-ului de descarcare:", "Save WBT with the following name", 1)
Range("L2").Value = myValue
Dim CopyToCSV()
Dim MyPath As String
Dim MyFileName As String
Sheets("Manual Discharge WBT").EnableCalculation = True
MyPath = "\\FILES\Transfer\~~TTS Import (do not delete)~~\Import Files\"
MyFileName = Range("L2") & " Discharge " & Format(CStr(Now), " dd_mm_yyyy_hh_mm")
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Sheets("Manual Discharge WBT").Copy
With ActiveWorkbook
.SaveAs Filename:= _
MyPath & MyFileName, _
FileFormat:=xlCSVWindows, _
CreateBackup:=False
.Close False
MsgBox "Fisierul tau s-a salvat ca: " & MyFileName
End With
The solution is, you will have to save your AnalysisResults and Join functions as an add-in file .xlam and add to excel at Developer->Add-ins. Doing it this way the above code worked for me when saving to CSV without #NAME?
What was happening here was that when excel is trying to save the file to CSV, it doesn't know what the AnalysisResults function is.
I’m getting an error 1004 with my code which takes data from closed workbooks in a list. The code functions as it should and retrieves the values without an issue, however it still brings up the error message. I’m probably missing something very obvious so I’d appreciate any help anyone can provide. Below is my code:
Sub ExecMacro4Excel()
Dim path As String
Dim workbookName As String
Dim worksheetName As String
Dim cell As String
Dim returnedValue As String
Dim lRow, x As Integer
Dim wbName As String
On Error GoTo PROC_ERR
lRow = Sheets("Raw Data").Range("C" & Rows.Count).End(xlUp).Row
path = Sheets("Front").Range("B4").Value
worksheetName = "Template"
cell = "J2"
x = 1
Do
x = x + 1
workbookName = Sheets("Raw Data").Range("C" & x).Value
returnedValue = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cell).Address(True, True, -4150)
Sheets("Raw Data").Range("I" & x) = ExecuteExcel4Macro(returnedValue)
Loop Until x = lRow
PROC_ERR:
MsgBox "Error: (" & Err.Number & ") " & Err.Description, vbCritical
End Sub
To further clarify, below shows the location where the data is the 1row variable is located and where the data will be put:
http://i.imgur.com/1UcuTd8.png
In addition here is the spreadsheet where the original data is kept and is the same for all of the files:
http://i.imgur.com/j40FD3z.png
And finally, this is the error box reads: "error 1004: A formula in this worksheet contains one or more invalid references. Verify your formulas contain a valid path, workbook, range name and cell reference".
Not sure why you want to use xlR1C1 for the range address, you might have just missed the = at the beginning of returnedValue. You can do it more simpler (assuming path will not change):
Sub ExecMacro4Excel()
Const worksheetName = "Template"
Const cell = "$J$2"
Dim path As String
Dim workbookName As String
'Dim worksheetName As String
'Dim cell As String
Dim returnedValue As String
Dim lRow, x As Integer
Dim wbName As String
On Error GoTo PROC_ERR
path = Sheets("Front").Range("B4").Value
If Right(path, 1) <> Application.PathSeparator Then path = path & Application.PathSeparator
lRow = Sheets("Raw Data").Range("C" & Rows.Count).End(xlUp).Row
For x = 2 To lRow
workbookName = Sheets("Raw Data").Range("C" & x).Value
returnedValue = "='" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cell).Address
Sheets("Raw Data").Range("I" & x).Formula = returnedValue
Next
PROC_ERR:
MsgBox "Error: (" & Err.Number & ") " & Err.Description, vbCritical
End Sub
I managed to solve this issue myself. The problem was that the list of file names was copied from another list and pasted in. The way I coded it the area selected wasn't done by finding the last row and copying only that section, instead it copied a finite number of cells, which included the data AND blank cells. So as the files were accessed the code worked fine, but when it came to the one following which had a blank cell it caused an error to occur.
I was wondering if anyone knew how one can reference a cell from a closed workbook using VBA.
I know how to reference a range of cells using ADO and SQL but I don't know how to create a SQL query for a specific cell.
While browsing the internet i came across some code that uses "ExecuteExcel4Macro" but I am unable to find any real documentation for this function/command. In fact the documentation on the MSDN website regarding this command is rubbish and vague and quit frankly not helpful at all.
Anyway I digress; Ideally, I would like to call on a cell from an external workbook without having to open said workbook. The code I am trying to get to work is as follows:
Sub update_overview()
Dim wbPath As String
Dim wbName As String
Dim wsName As String
Dim cellRef As String
Dim data As Variant
wbPath = "C:\examplepath\"
wbName = "Core (N)i.xls"
wsName = "Sheet1"
cellRef = "C5"
'data = GetData(wbPath, wbName, wsName, cellRef)
ThisWorkbook.Activate
Sheets("Overview").Select
With Selection
ActiveSheet.Range("C5").Clear
ActiveSheet.Range("C5").Select
ActiveCell = GetData(wbPath, wbName, wsName, cellRef)
End With
End Sub
Private Function GetData(ByVal wbPath As String, _
wbName As String, wsName As String, cellRef As String) As Variant
Dim arg As String
GetData = ""
arg = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)
GetData = ExecuteExcel4Macro(arg)
End Function
When i run the macro the only thing it returns is #REF
I have also tried:
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
When the code reaches MsgBox I get a type missmatch error. If i get rid of the msgbox command and try to continue to paste to the cell with
ThisWorkbook.Activate
Sheets("Overview").Select
With Selection
ActiveSheet.Range("C5").Clear
ActiveSheet.Range("C5").Select
ActiveCell = ExecuteExcel4Macro(Ret)
I still get the #REF! error
Can anyone tell me:
1) is this the best technique to be using?
2) What is wrong with my code? and,
3) Is there a better way to reference a single cell from an external workbook using ADO or DOA or a technique i am unaware of.
Also does anyone know of any extensive documentation on how to use the ExecuteExcel4Macro function.
Please help; Thanks
FYI I am on excel 2003
You could try something like this:
arg = "='" & wbPath & "[" & wbName & "]" & wsName & "'!" & cellRef
Sub Test()
Dim wbName As String
Dim wbPath As String
Dim wsName As String
Dim cellRef As String
Dim calcState As Long
calcState = Application.Calculation
wbPath = "C:\users\david_zemens\"
wbName = "a report.xlsx"
wsName = "Sheet1"
cellRef = Range("B2").Address
Dim arg As String
arg = "='" & wbPath & "[" & wbName & "]" & wsName & "'!" & cellRef 'Range(cellRef).Address(True, True, xlR1C1)
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
ActiveCell.Value = arg
ActiveCell.Value = ActiveCell.Value 'essentially a paste/values over the formula.
Application.DisplayAlerts = True
Application.Calculation = calcState
End Sub