Using GetValuePrice and receiving error because ref is empty - excel

I am pulling information from worksheets that are in a folder - all files are using the same template - into another worksheet to create a matrix of the information.
I am only pulling three cells from each template and the first two are pulling correctly, because they are on one sheet of the template model but the third is not populating and I am receiving an error.(Run time error 1004. Method of Range of Object_global failed") I am not sure if that has anything to do with my error or if it's something occurring before then.
I have the following:
Private Function GetValuePrice(path, file, sheet, ref)
Dim arg As String
If Right(path, 1) <> "\" Then path = path & "\"
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xR1C1)
Debug.Assert Var = 0
GetValuePrice = ExecuteExcel4Macro(arg)
End Function
I am receiving an error and when I hit debug it shows me that ref is empty.
(Run time error 1004. Method of Range of Object_global failed")
This is the code i have in the button to pull from the tabs Workload and Project Info from the templates in the folder.
Private Sub CommandButton21_Click()
ThisWorkbook.Sheets("Sheet1").Range("a166:h500").ClearContents
ThisWorkbook.Sheets("Sheet1").Range("j166:v500").ClearContents
Application.Calculation = xlCalculationManual
ProjectInfo
WorkLoad
Application.Calculation = xlCalculationAutomatic
End Sub
I'm not sure what to fix because I run another matrix with the same code but change the file destination and it works.

In my second sub, i was not pulling the correct variable to display in the matrix. I had declared "CC" but was displaying "AA". Therefore changed the AA to CC and it worked.

Related

Excel VBA code error '1004' while searching external links

I need your help. I found the attached vba code but when I run the code I am getting a very strange 1004 error. Could you please give an explanation or try to fix this error?
Thank you so much all!
' Module to remove all hidden names on active workbook
Sub Remove_Hidden_Names()
' Dimension variables.
Dim xName As Variant
Dim Result As Variant
Dim Vis As Variant
' Loop once for each name in the workbook.
For Each xName In ActiveWorkbook.Names
'If a name is not visible (it is hidden)...
If xName.Visible = True Then
Vis = "Visible"
Else
Vis = "Hidden"
End If
' ...ask whether or not to delete the name.
Result = MsgBox(prompt:="Delete " & Vis & " Name " & _
Chr(10) & xName.Name & "?" & Chr(10) & _
"Which refers to: " & Chr(10) & xName.RefersTo, _
Buttons:=vbYesNo)
' If the result is true, then delete the name.
If Result = vbYes Then xName.Delete
' Loop to the next name.
Next xName
End Sub
These Excel built-in range names appear in the Excel name manager when using SUMIFS,IFERROR, COUNTIFS and other formulas.
There are a lot of ways around this, as suggested in the comments.
You can add either of these:
If Not xName.Name Like "_xlfn*" Then
'Or
If InStr(xName.Name, "_xlfn") = 0 Then
first thing in the loop (don't forget to close it), or something similar.
If you for some reason still want to see it, you can add it to the delete if:
If Result = vbYes And Not xName.Name Like "_xlfn*" Then xName.Delete

Excel macro not working after Windows update - Office 365

After a recent windows update, a previous Excel vba script that was working, no longer functions correctly.
The macro operation, when working, opens a csv file that is defined in the active workbook as String aString. The csv file contains a list of variables and corresponding values for those variables. The macro returns the original active workbook and reads the defined named cells in the active workbook and updates those named cells with the values defined in the csv file.
The issue appears to be that despite returning to the original active workbook the command to generate the For loop to cycle through the named cells no longer returns a value for the variable name or which worksheet the variable lives in.
The command is:
' Process to update name values
Workbooks(strWorkBook).Activate
' Windows(strWorkBook).Activate
' Dim nm As Variant
' For Each nm In ActiveWorkbook.Names
For Each nm In Workbooks(strWorkBook).Names
varname = nm.Name
MsgBox "varname " & varname & " nm " & nm
varsheet = Range(nm).Parent.Name
MsgBox "varsheet " & varsheet
The message for the varname is now:
The message should read varname aString nm $D$4
Pretty sure it is update version related, as in Excel build Version 1902 (Build 11328.20318) it works but not in Version 2002 (Build 12527.21416)
Thanks in advance for your help. Related forums point to security update issues with Windows but no solutions I can implement yet.
======================================================
Update from further testing:
I created a new workbook and built the macro that is failing in the new workbook using Excel Version 2002 (Build 12527.21416). The macro runs perfectly in the new version of the Excel file but continues to produce the error message above in the legacy file.
I'm suspecting there are some issues related to security updates in the Version 2002 build that are not compatible with the Version 1902 build but cannot identify what the issues are.
The macro that runs in the new version but not the original document is:
Public Sub testName()
Dim filePath As String
Dim inFilePath As String
Dim inCase As String
'On Error GoTo ErrorHandler
Application.ScreenUpdating = False
Application.EnableEvents = False
'----------------------------------
' Find path for input file
strWorkBook = ActiveWorkbook.Name
' MsgBox strWorkBook
filePath = Range("aString").Value
tmpsep = InStrRev(filePath, "\")
' Input file workbook name
inCase = Right(filePath, Len(filePath) - tmpsep)
'Input file full path
inFilePath = Left(filePath, Len(filePath) - Len(inCase))
' Open input data file
Workbooks.Open Filename:=filePath
'' Find last row in file
' Call FindLastRow.FindLastRow(lRow)
' rngend = lRow + 2
'' MsgBox rngend
Workbooks(strWorkBook).Activate
'
' VBA script to read external CSV file' For Each nm In ActiveWorkbook.Names
For Each nm In Workbooks(strWorkBook).Names
varname = nm.Name
MsgBox "varname " & varname & " nm " & nm
varsheet = Range(nm).Parent.Name
MsgBox "varsheet " & varsheet
varcell = nm.RefersToRange.Address(False, False)
NextIteration:
Next nm
End Sub
Your problem stems from the misdeclaration of the variable Nm. In fact, it's not declared (and you are missing Option Explicit at the top of your module) which makes it a Variant. Excel appears unable to fit the Name object into the variant as you intend within the rather complicated environment you create (more about that further down). This code will work.
Dim Nm As Name
Dim varName As String
Dim varSheet As String
Dim varCell As String
' For Each Nm In ActiveWorkbook.Names
For Each Nm In Workbooks(strWorkBook).Names
With Nm
varName = .Name
varSheet = .RefersToRange.Parent.Name
varCell = .RefersToRange.Address(0, 0)
End With
MsgBox "Named range """ & varName & """ refers to range" & vbCr & _
varCell & " on sheet """ & varSheet & """."
Next Nm
I tested the above code on the ActiveWorkbook but it should work on any other as well. I tested in Excel 365 but that shouldn't make a difference, either.
The complication mentioned above stems from this part of your code, Range(nm).Parent.Name. In this context nm is a string. But in the context of your loop nm is a Name object. So, whereas in the older version apparently the default property of the Name object was the referenced range address it now would appear to be something else. It doesn't really matter because the Name object has several properties from which the referenced range can be extracted as a range or its address, and once you specify the one you want to use there is no need to ask VBA to use the default.
Incidentally, Range("anything")will always be on the ActiveSheet, and Range("Sheet13!A2:A4").Parent will return an error rather than Sheet13. Therefore, if you need to know the sheet of the range on which the named range resides you should look for another method of getting at it.
Problem solved thanks to this thread stackflow thread and user Jenn.
It seems that between Excel V1902 and V2002 a hidden variable _xlfn.SINGLE exists in the workbook. When the macro loops through, it sees the named range, cannot resolve its address or sheet location and stops. Not until running Jenn's code could I see the hidden variable.
The easiest solution was to include an IF loop to bypass this variable if defined and continue as normal (as per below). The sheet is working now but I will not get those 2 days of my life back.
For Each Nm In Workbooks(strWorkBook).Names
If Nm.Name Like "_xlfn*" Then
GoTo NextIteration
End If
With Nm
varName = .Name
varSheet = .RefersToRange.Parent.Name
varCell = .RefersToRange.Address(0, 0)
End With
MsgBox "Named range """ & varName & """ refers to range" & vbCr & _
varCell & " on sheet """ & varSheet & """."
NextIteration:
Next Nm
Thanks to those who commented on the thread and Variatus I will update those declarations.

Saving excel xlsm file not working due to error

I have this macro which is updating some tables and it has been working fine for the past two weeks, however it suddenly started giving me 1004 runtime error - initially it was runtime error 1004 method saveas of object _workbook failedub SaveAs(), now it is simply Run Time Error 1004 “Application-Defined or Object-Defined Error.
I suspect is has something to do with saving the file as that's the point it gives me error, everything else works fine. I have separated the saving code in a different macro and its still giving this error.
I have tried to make the path string into one piece (Mth var is a variable we change each month of reporting and is fed off a sheet value but have had to add it manually for testing purpose). Initially Path and Filename missed the ("S") at the end as I thought the names might be conflicting with something in the library.
Please note, before the code was using ActiveWorkbook.Saveas and was working fine I am not sure it's a problem of Excel knowing which sheet or workbook to look at.
How do I fix this? Please see code below:
ThisWorkbook.Activate
Dim Mth As Integer
Mth = 4
Dim FileNames As String
Dim Paths As String
Dim Fullstring As String
Application.DisplayAlerts = False
Paths = "\\RL1VMFIL02\Finance$\Financial Management\SITES & SERVICES\Corporate\2020-21\C - Statements & Trends" & "\M" & Mth & "\"
FileNames = Format(Now(), "dd.mm.yy") & " Budget Statement & Trend M" & Mth & " - " & Format(Now(), "hh.mm") & ".xlsm"
Fullstring = Paths & FileNames
ThisWorkbook.Activate
ThisWorkbook.SaveAs Fullstring
Application.DisplayAlerts = True
End Sub
This has been fixed by making sure the path folder exists as adviced by #RustyBucketBay & #GMalc.
Explicitly, the Month path included a 0 so it should've been either Mth var = '04 rather than 4 or path "\M0" & Mth & ""
Many thanks guys for the help!

How to Throw Error with Excel Prompt in VBA

I have some code which looks for a value with a given sheet name in two separate workbooks.
What I want to do is when the first workbook does not have the sheet, instead of the following prompt coming up, it cancels/throws an error and using the error handling goes to the second spreadsheet. How do I do this?
Currently I am using this code to achieve this:
fFormString1 = "'" & wkBookRef1 & firstShtName & "'!$L$6/1000"
fFormString2 = "'" & wkBookRef2 & firstShtName & "'!$L$6/1000"
Application.DisplayAlerts = False 'Does nothing to the prompt
On Error GoTo tryTwo 'Following only throws error when prompt is canceled
ThisWorkbook.Sheets("Place").Range("E53").Formula = "=" & fFormString1
GoTo endTen
tryTwo:
ThisWorkbook.Sheets("Place").Range("E53").Formula = "=IFERROR(" & fFormString2 & ","""")"
On Error Resume Next
endTen:
Application.DisplayAlerts = True 'Does nothing to the prompt
Note: I wish to do this with the spreadsheet closed ideally. Or visually not present to improve speed and smoothness of operation for my client.
ExecuteExcel4Macro will return a value from a closed workbook. If the worksheet doesn't exist it will throw an error 1004 'A formula in this worksheet contains one or more invalid references.
ExternalWorksheetExists uses this to test it the worksheet exist.
Function ExternalWorksheetExists(FilePath As String, FileName As String, WorksheetName As String) As Boolean
If Right(FilePath, 1) <> "\" Then FilePath = FilePath & "\"
On Error Resume Next
Call ExecuteExcel4Macro("'" & FilePath & "[" & FileName & "]" & WorksheetName & "'!R3C3")
ExternalWorksheetExists = Err.Number = 0
On Error GoTo 0
End Function
When using ExecuteExcel4Macro, all references must be given as R1C1 strings. Here is an example of a valid string:
ExecuteExcel4Macro("'C:\Users\tinzina\Documents\[Book1.xlsm]Sheet1'!R6C12")
Borrowing heavily from Thomas' answer (full credit is due). However it seems that this didn't work for you.
Use ExecuteExcel4Macro but ascribe the value to the variable val. Then check if this is the error you are looking for Error(2023).
Please find the code below:
'Check if the sheet exists in the workbook, used to check which forecast file one should look in
Function ExtSheetExists(formString) As Boolean 'Form string is a formula string with both the worksheet and the workbook
Dim val As Variant
'Tries to execute formula and throws error if it doesn't exist
On Error Resume Next
val = ExecuteExcel4Macro(formString)
ExtSheetExists = (val <> Error(2023)) 'Returns False if the sheet does not exist based on Error 2023
On Error GoTo 0
End Function

ExecuteExcel4Macro Method fails in Excel 2011 on Mac with 1004 Error

So I'm another one of those wanting to use the ExecuteExcel4Macro Method call to retrieve data from specific cells and lookup ranges in closed workbooks. I have seen lots of examples and answers to problems here and elsewhere. I am (or will be) using a variation of a routine credited to John Walkenbach, and referenced here and on other forums. (See thread for 9311188.)
The call to ExecuteExcel4Macro fails with an error "1004 - Method 'ExecuteExcel4Macro' of object '_Global' failed". For me, that's not a lot to go on. I have double checked the directory paths, file and sheet names, all that. The DIR() function finds the file okay. I've even put the files in the root directory to eliminate path complexities or too-long of an argument to the Method. One complication is that I'm on a Mac with OS 10.8 and using Excel 2011. Mac OS uses ":" instead of "" for directory delimiters.
But I don't really need to get into all that because the problem seems to be something fundamental about the cell reference addressing. I can't get ExecuteExcel4Macro to execute successfully within the same worksheet with an Excel Function that addresses any cell or range, never mind about a remote, closed worksheet reference. So I have condensed my example code to the essentials – no remote reference, just functions on cells in one worksheet.
In the example below I have a simple routine that executes some sample Excel Functions and displays a MessageBox with either the successful result or the error message, along with the argument to the Method call. There's also a function that will convert the A1 style references to R1C1 when needed. The list of Functions are within the routine, just comment/uncomment as needed to execute whichever one to test.
Function MakeR1C1(A1Formula As String) As String
MakeR1C1 = Application.ConvertFormula( _
Formula:=A1Formula, _
fromReferenceStyle:=xlA1, _
toReferenceStyle:=xlR1C1, _
ToAbsolute:=xlAbsolute)
End Function
Sub TestExcel4Macro()
On Error GoTo ErrorTrap
Dim arg As String
' arg = "GET.CELL(42)"
' arg = "CHAR(65)"
' arg = "LEN(""ABCDE"")"
' arg = "SUM(2,5,8)"
' arg = "INFO(""directory"")"
' arg = "INFO(""numfile"")"
' arg = "SUM(A32:A34)"
' arg = "SUM(ValList)"
' arg = MakeR1C1("SUM(A32:A34)")
' arg = "SUM(R32C1:R34C1)"
Rtn = ExecuteExcel4Macro(arg)
MsgBox "COMPLETED" & Chr(13) & _
"arg: " & arg & Chr(13) & _
"Return Value: " & Rtn
Exit Sub
ErrorTrap:
Beep
MsgBox "FAILED" & Chr(13) & _
"arg: " & arg & Chr(13) & _
"Error number: " & Err & Chr(13) & _
Error(Err)
End Sub
The first six all work just fine, returning the values you would expect:
arg = "GET.CELL(42)"         This returns the left margin, or whatever that is;
arg = "CHAR(65)"             Good, you get an "A" for that;
arg = "LEN(""ABCDE"")"       Nice, that's a 5;
arg = "SUM(2,5,8)"           Okay, 15;
arg = "INFO(""directory"")"  Yep, the directory path of the active workbook with the macro;
arg = "INFO(""numfile"")"    And the number of sheets in the workbook (plus 1? whatever).
So from this I know I'm accessing the Method correctly; it does work; you don't use the "=" in the argument; and the two INFO() Functions tell me it's able to access info about this workbook; i.e. it doesn't require explicit full directory pathway to find itself.
Now some functions that make reference to cells in the worksheet. These all work fine as a Formula in a cell in the worksheet.
But they fail as a call to the Method, with the respective error codes:
arg = "SUM(A32:A34)"            13 - Type mismatch
As expected, the Method requires R1C1 style references.
arg = "SUM(ValList)"            13 - Type mismatch
Okay, not too surprising, so it won't work with a named range. Too bad, I was counting on that.
arg = MakeR1C1("SUM(A32:A34)")  1004 - Method 'ExecuteExcel4Macro' of object '_Global' failed
Now the puzzlement. The MakeR1C1() converts the A1 addressing okay to "SUM(R32C1:R34C1)".
arg = "SUM(R32C1:R34C1)"        1004 - Method 'ExecuteExcel4Macro' of object '_Global' failed
And setting the argument explicitly with the R1C1 style fails the same.
I'll be really embarrassed if this is due to something simple and obvious. But I'll risk it because I'm stumped.
If it's not so simple then, Gurus, have at it. If I get this simple reference addressing problem figured out, then the remote file reference should fall into place, too.
I'll be especially appreciative of anyone who can test these in a Windows version and let me know what you get. That's what I'm most worried about – a Mac incompatibility that I can't fix.
Thanks to all in advance.
PS: I hope I have marked up all the above correctly, I tried.
Edit: Maybe I should have mentioned that to run my TestExcel4Macro() subroutine, I just mash the F5 key while in the VBA editor.
Quote:
The Microsoft Excel 4.0 macro isn't evaluated in the context of the
current workbook or sheet. This means that any references should be
external and should specify an explicit workbook name. For example, to
run the Microsoft Excel 4.0 macro "My_Macro" in Book1 you must use
"Book1!My_Macro()". If you don't specify the workbook name, this
method fails.
Here is what worked for me (MS Excel 2010 under Windows smthg): you have to specify the workbook + Sheet before referring to the Cells; and also make the R1C1 conversion.
Sub TestExcel4Macro()
On Error GoTo ErrorTrap
Dim arg As String
Dim this_workbook As String
' workbook named "myBook" having a sheet called "mySheet" where my data is
this_workbook = "[myBook.xlsm]mySheet!"
arg = "SUM(" & this_workbook & "A32:A34)"
arg = MakeR1C1("SUM(A32:A34)")
Rtn = ExecuteExcel4Macro(arg)
MsgBox "COMPLETED" & Chr(13) & _
"arg: " & arg & Chr(13) & _
"Return Value: " & Rtn
Exit Sub
ErrorTrap:
Beep
MsgBox "FAILED" & Chr(13) & _
"arg: " & arg & Chr(13) & _
"Error number: " & Err & Chr(13) & _
Error(Err)
End Sub
Have you tried defining arg as Variant instead of String?

Resources