What is error 2015 in excel vba

I have to following code snippet …

  Public Sub FindText(path As String, file As String)
    Dim Found As Range

    myText = "test("

    MacroBook = ActiveWorkbook.Name

    ' Open the File
    Workbooks.Open path & file, ReadOnly:=True, UpdateLinks:=False
    For Each ws In Workbooks(file).Worksheets
     With ws

       Set Found = .UsedRange.Find(What:=myText, LookIn:=xlFormulas, _
                      LookAt:=xlPart, MatchCase:=False)

       If Not Found Is Nothing Then
        ' do stuff
        ' ...

I see in the debugger that Found contains Error 2015! The sheet contains the text I want in the formula.

Any ideas why I’m getting the error?

Thanks

asked Feb 25, 2014 at 12:22

Rueful Rabbit's user avatar

Rueful RabbitRueful Rabbit

1111 gold badge2 silver badges8 bronze badges

5

As follow up from comments to the Q, Error 2015 occurs because your formula in the sheet returns #VALUE! error. You can handle it using IsError:

If Not Found Is Nothing Then
    If Not IsError(Found) Then
       ' do sth
    End If
End If

answered Feb 25, 2014 at 13:41

Dmitry Pavliv's user avatar

Dmitry PavlivDmitry Pavliv

35.2k13 gold badges79 silver badges80 bronze badges

1

You don’t need to use ‘Set’ in your code. You only use this to assign a reference to an object. Try:-

For Each ws In Workbooks(file).Worksheets
     With ws

       Found = .UsedRange.Find(What:=myText, LookIn:=xlFormulas, _
                      LookAt:=xlPart, MatchCase:=False)

       If Not Found Is Nothing Then
        ' do stuff
        ' ...

Hopefully this should work.

answered Feb 25, 2014 at 12:28

Mat Richardson's user avatar

Mat RichardsonMat Richardson

3,5584 gold badges32 silver badges55 bronze badges

2

Содержание

  1. Как исправить ошибку Microsoft Excel 2015
  2. Проверка «Excel Error 2015»
  3. Почему возникает ошибка времени выполнения 2015?
  4. Классические проблемы Excel Error 2015
  5. Источник ошибок Excel Error 2015
  6. Функция VBA Evaluate не работает. Ошибка 2015
  7. Excel VBA — Array Formula returns #VALUE! (Error 2015) in case a cell contains more than 255 characters
  8. Dutch Gemini’s Weblog Pages
  9. August 7, 2009
  10. Error 2015 using Application.Evaluate in Excel VBA
  11. VBA Evaluate function not working. Error 2015
  12. 1 Answer 1

Как исправить ошибку Microsoft Excel 2015

Номер ошибки: Ошибка 2015
Название ошибки: Excel Error 2015
Описание ошибки: Ошибка 2015: Возникла ошибка в приложении Microsoft Excel. Приложение будет закрыто. Приносим извинения за неудобства.
Разработчик: Microsoft Corporation
Программное обеспечение: Microsoft Excel
Относится к: Windows XP, Vista, 7, 8, 10, 11

Проверка «Excel Error 2015»

«Excel Error 2015» обычно называется формой «ошибки времени выполнения». Когда дело доходит до программного обеспечения, как Microsoft Excel, инженеры могут использовать различные инструменты, чтобы попытаться сорвать эти ошибки как можно скорее. Ошибки, такие как ошибка 2015, иногда удаляются из отчетов, оставляя проблему остается нерешенной в программном обеспечении.

«Excel Error 2015» может возникнуть у пользователей Microsoft Excel даже при нормальном использовании приложения. Когда это происходит, конечные пользователи могут сообщить Microsoft Corporation о наличии ошибок «Excel Error 2015». Разработчик сможет исправить свой исходный код и выпустить обновление на рынке. Если есть запрос на обновление Microsoft Excel, это обычно обходной путь для устранения проблем, таких как ошибка 2015 и другие ошибки.

Почему возникает ошибка времени выполнения 2015?

Проблема с исходным кодом Microsoft Excel приведет к этому «Excel Error 2015», чаще всего на этапе запуска. Проанализируем некоторые из наиболее распространенных причин ошибок ошибки 2015 во время выполнения:

Ошибка 2015 Crash — это типичная ошибка 2015 во время выполнения, которая полностью аварийно завершает работу компьютера. Это происходит много, когда продукт (Microsoft Excel) или компьютер не может обрабатывать уникальные входные данные.

Утечка памяти «Excel Error 2015» — Когда Microsoft Excel обнаруживает утечку памяти, операционная система постепенно работает медленно, поскольку она истощает системные ресурсы. Потенциальные триггеры могут быть бесконечным циклом, что приводит к тому, что работа программы запускается снова и снова.

Ошибка 2015 Logic Error — Компьютерная система создает неверную информацию или дает другой результат, даже если входные данные являются точными. Обычные причины этой проблемы связаны с ошибками в обработке данных.

Microsoft Corporation проблемы с Excel Error 2015 чаще всего связаны с повреждением или отсутствием файла Microsoft Excel. Как правило, самый лучший и простой способ устранения ошибок, связанных с файлами Microsoft Corporation, является замена файлов. Кроме того, некоторые ошибки Excel Error 2015 могут возникать по причине наличия неправильных ссылок на реестр. По этой причине для очистки недействительных записей рекомендуется выполнить сканирование реестра.

Классические проблемы Excel Error 2015

Частичный список ошибок Excel Error 2015 Microsoft Excel:

  • «Ошибка Excel Error 2015. «
  • «Недопустимый файл Excel Error 2015. «
  • «Извините, Excel Error 2015 столкнулся с проблемой. «
  • «Не удается найти Excel Error 2015»
  • «Excel Error 2015 не найден.»
  • «Ошибка запуска программы: Excel Error 2015.»
  • «Excel Error 2015 не работает. «
  • «Excel Error 2015 остановлен. «
  • «Неверный путь к программе: Excel Error 2015. «

Проблемы Microsoft Excel Excel Error 2015 возникают при установке, во время работы программного обеспечения, связанного с Excel Error 2015, во время завершения работы или запуска или менее вероятно во время обновления операционной системы. Запись ошибок Excel Error 2015 внутри Microsoft Excel имеет решающее значение для обнаружения неисправностей электронной Windows и ретрансляции обратно в Microsoft Corporation для параметров ремонта.

Источник ошибок Excel Error 2015

Проблемы Excel Error 2015 вызваны поврежденным или отсутствующим Excel Error 2015, недопустимыми ключами реестра, связанными с Microsoft Excel, или вредоносным ПО.

В частности, проблемы с Excel Error 2015, вызванные:

  • Недопустимые разделы реестра Excel Error 2015/повреждены.
  • Вирус или вредоносное ПО, которые повредили файл Excel Error 2015 или связанные с Microsoft Excel программные файлы.
  • Другая программа злонамеренно или по ошибке удалила файлы, связанные с Excel Error 2015.
  • Другое программное приложение, конфликтующее с Excel Error 2015.
  • Неполный или поврежденный Microsoft Excel (Excel Error 2015) из загрузки или установки.

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Источник

Функция VBA Evaluate не работает. Ошибка 2015

Я пытаюсь подключить OsiSoft Pi Datalink к Excel VBA и поместить результат в переменную для дальнейшей обработки VBA.

При запуске команды в ячейке Excel она работает нормально, но когда я пытаюсь запустить ее в VBA, я получаю «Ошибка 2015».

Это код, который отлично работает в ячейке:

Преобразование этого в VBA:

Я проверил ссылки VBA, как показано ниже, и они также кажутся правильными:

В руководствах пользователя или доступной информации, которую я мог бы найти в Интернете, нет информации о правильном подключении VBA к Pi Datalink.

Я нашел это в stackoverflow, но не объяснил проблему:

Получение данных из PI DataLink с помощью VBA

Возможно, мне не хватает чего-то действительно простого, но похоже, что я выполняю в VBA тот же код, что и в ячейке. Ячейка возвращает значение, а VBA просто возвращает ошибку.

Заранее спасибо за вашу помощь

Это давняя проблема / ограничение оценки. Если длина возвращаемого значения> 255 символов, появляется ошибка 2015. Насколько мне известно, теперь есть обходной путь, по крайней мере, с Оценивать. Проверьте, включена ли библиотека COM, т.е. предоставляет / разрешает использование методов в VBA напрямую.

@cyboashu Ты имел ввиду есть обходной путь нет?

Я ничего не знаю, но это только я. (и еще несколько) 🙂 Вижу, я написал сейчас же вместо нет, длинный день и мало пива !!

Большое спасибо за Ваш ответ. Я разговариваю с OsiSoft, поэтому проверю, включен ли он.

Мысль, которую делает cyboashu, хорошая. Однако также может быть, что вы получаете эту ошибку из-за вашего синтаксиса.

При использовании Evaluate вы должны передать строку именно так, как вы хотите, чтобы она оценивалась. Ваш код передает имя переменных вместо их значений. Если бы я мог упростить пример. Следующий код вернет ошибку (в данном случае 2029, это ошибка #NAME):

В этом примере вам нужно будет создать строку, чтобы вычислить стоимость txt, например:

Я подозреваю, что это причина, потому что, если в требуемой строке отсутствуют кавычки, Evaluate вернет ошибку 2015. Это могло бы сделать это, например:

У меня нет библиотеки для проверки вашего точного кода, но попробуйте переписать строку оценки, чтобы вместо этого включить значения ваших переменных, и не забудьте передать также кавычки.

Спасибо! Я попробую это сделать, когда снова получу доступ к базе данных.

Источник

Excel VBA — Array Formula returns #VALUE! (Error 2015) in case a cell contains more than 255 characters

Dear all I am using an array formula and pass the result to a VBA macro, which means the result of the formula is passed as array to my macro.

In some cases I get in the array a #VALUE (error 2015) and I have no clue why. When I play arround with the affected cell where it gets the data from then it is happening when the cell has quite an amount of characters (

Has anyone a clue what I can try to solve the isuse?

the IF(‘sheet’!$G$1:$G$2000=A1;’sheet’!$F$1:$F$2000) part returns an array like . This one I pass to my mVBA function removeElementsFrom2DimArray to remove the FALSE elements

Now it seems that the IF(‘sheet’!$G$1:$G$2000=A1;’sheet’!$F$1:$F$2000) return in some cases #VALUE(Error 2015) for some of the elements i.e.

UPDATES:

I tried to modify to pass over arr as Variant or ByVal . It did not made any difference.

I tried to modify to pass over arr as array arr() with and without the () . It did not made any difference.

If I reduce the number of chars in the affected cell ‘sheet’!$F$1:$F$2000 to below 256 chars then it works!

If I use just the formula <=IF(sheet!$G$1:$G$2000=A1;sheet!$F$1:$F$2000)>(array formula) then it works too!

so I assume there is a limitation in passing arrays from native formulas to own functions? So that values in the array with more than 255 chars get passed with #VALUE! error?

Any idea? I am using Excel 2010 Plus (v14.0.7)

Источник

Dutch Gemini’s Weblog Pages

August 7, 2009

Error 2015 using Application.Evaluate in Excel VBA

Since a while I am using Application.Evaluate because of the fact that you can craft formulas as strings and have Excel VBA compute them for you.

Only recently I discovered that some of the cells in a workbook contained #VALUE? instead of a sound value. After some investigation I found out that, without raising any error at application level (in VBA), the Application.Evaluate function failed consistently with this error whenever a particular condition occurred.

This condition is related to limits in the underlying software layer of Excel, the one that runs Application.Evaluate.

Apparently this particular error occurs when the parsed function returns a string value having a length above 255 characters. As long as the length of the string is less than or equal to 255 characters, the return value is the desired string. Above 255 characters, the function “crashes”.

In my case, I was not immediately attended on this error because I used a Variant to store the returned value from Application.Evaluate (sample code):

If I would have used a String to store the value, I would probably have gotten a “Runtime Error 13 – Type Mismatch” with Excel booming out of my routine without any debugging possibility (sample code):

To catch problems, I now completed code with an If statement (sample code):

There seem to be more Excel functions that suffer from this 255 character limit, but could not establish which. For the moment, I will apply some workarounds until it gets solved by Microsoft.

Источник

VBA Evaluate function not working. Error 2015

I am trying to connect OsiSoft Pi Datalink with Excel VBA and put the output into a variable for further VBA procesing.

When running the command in the excel cell it works fine but when I try to run it in VBA I get “Error 2015”

This is the code that is working fine in the cell:

Converting this to VBA:

I have checked the VBA references as below and they also seem correct:

There is no information in the user guides or available that I could find on the internet for corretcly connecting VBA to Pi Datalink.

I found this on stackoverflow but it didn’t explain the issue:

I am possibly missing somthing really basic but it seems like I am executing the exact same code in VBA as in the cell. The cell is returning a value and VBA is just returning an error.

Thanks in advance for your help

1 Answer 1

The point that cyboashu makes is a good one. It might also be the case, though, that you are receiving this error because of your syntax.

When using Evaluate , you must pass in the string exactly as you want it to be evaluated. Your code is passing the name of the variables instead of their values. If I could simplify an example. The following code would return an Error (2029 in this case, which is a #NAME error):

In this example you would need to create the string so that the value of txt were evaluated, like so:

I suspect this is the cause because if inverted commas are missing from a required string, then Evaluate will return a 2015 Error. This would do it for example:

I don’t have the library to test your exact code, but try rewriting your evaluation string to incorporate the values of your variables instead and remember to pass in the inverted commas too.

Источник

Error 2015 using Application.Evaluate in Excel VBA

Since a while I am using Application.Evaluate because of the fact that you can craft formulas as strings and have Excel VBA compute them for you.

Only recently I discovered that some of the cells in a workbook contained #VALUE? instead of a sound value. After some investigation I found out that, without raising any error at application level (in VBA), the Application.Evaluate function failed consistently with this error whenever a particular condition occurred.

This condition is related to limits in the underlying software layer of Excel, the one that runs Application.Evaluate.

Apparently this particular error occurs when the parsed function returns a string value having a length above 255 characters. As long as the length of the string is less than or equal to 255 characters, the return value is the desired string. Above 255 characters, the function “crashes”.

In my case, I was not immediately attended on this error because I used a Variant to store the returned value from Application.Evaluate (sample code):

Dim vValue As Variant
vValue =  Application.Evaluate("GetData()") ' Error 2015 saved in vValue if GetData returns 255+ characters
ActiveCell.Value = vValue

If I would have used a String to store the value, I would probably have gotten a “Runtime Error 13 – Type Mismatch” with Excel booming out of my routine without any debugging possibility (sample code):

Dim sValue As String
sValue =  Application.Evaluate("GetData()") ' Run-time error if GetData() returns 255+ characters
ActiveCell.Value = sValue

To catch problems, I now completed code with an If statement (sample code):

Dim vValue As Variant
vValue =  Application.Evaluate("GetData()")
If (VBA.VarType(vValue) = vbError) Then 
    ActiveCell.Value = "String Overflow on GetData()"
Else
    ActiveCell.Value = vValue 
End If

There seem to be more Excel functions that suffer from this 255 character limit, but could not establish which. For the moment, I will apply some workarounds until it gets solved by Microsoft.

Dutch

fname returns the whole path/filename.

So if fName = C:My Documentsexcelbook5.xls, then this portion:

sh = «‘[» & fname & «]May’!»

will be essentially:

sh = «‘[C:My Documentsexcelbook5.xls]may’!»

And that’s not the way excel builds that formula.

If you drop that .open statement (probably there for testing???), you’d want
your formula to look more like:

=MATCH(1,(‘C:My Documentsexcel[book5.xls]May’!$A$1:$A$10=20)*….

And your formula had too many closing parentheses, too:

Option Explicit

Sub Macro5()
Dim mtchValue As Variant
Dim getvalue As Variant
Dim sh As String
Dim fname As Variant

fname = Application.GetOpenFilename
If fname = False Then
Exit Sub ‘cancel
End If

sh = MakeReferenceNicer(fname)

‘Workbooks.Open Filename:=fname

mtchValue = («MATCH(1,(» & sh & «A1:A10000=20)*» & _
«(» & sh & «B1:B10000=6)*» & «(» & sh & _
«C1:C10000=»»F»»)*» & «(» & sh & _
«E1:E10000=»»Escada»»),0)»)
If Not IsError(mtchValue) Then
getvalue = Application.Evaluate(«Index(» & sh & «F1:F10000,» _
& mtchValue & «)»)
End If

End Sub
Function MakeReferenceNicer(fname) As String

‘taking
‘»C:My Documentsexcelbook5.xls»
‘shooting for:
‘»‘C:My Documentsexcel[book5.xls]May’!»

Dim iCtr As Long
Dim myStr As String

For iCtr = Len(fname) To 1 Step -1
If Mid(fname, iCtr, 1) = «» Then
‘found that last backslash
myStr = «‘» & Left(fname, iCtr) & _
«[» & Mid(fname, iCtr + 1) & «]May’!»
Exit For
End If
Next iCtr

MakeReferenceNicer = myStr

End Function

Jeff wrote:


>
> Hello,
> I need help,
> This is my VBA macro
> Sub Macro5()
> Dim mtchValue As Variant
> Dim getvalue As Variant
> Dim sh As String
> Dim fname
> fname = Application.GetOpenFilename
> Workbooks.Open filename:=fname
> sh = «‘[» & fname & «]May’!»
> mtchValue = Application.Evaluate(«MATCH(1,(» & sh & «A1:A10000=20)*» &
> «(» & sh & «B1:B10000=6)*» & «(» & sh & «C1:C10000=»»F»»)*» & «(» & sh &
> «E1:E10000=»»Escada»»),0))»)
> If Not IsError(mtchValue) Then
> getvalue = Application.Evaluate(«Index(» & sh & «F1:F10000,» &
> mtchValue & «)»)
> End If
> Can anyone tell me why I have «Error 2015» on mtchvalue?
>
> End Sub
> —
> Regards,
> Jeff

Dave Peterson

AlastairFM

Posts: 10
Joined: Mon Feb 28, 2011 12:13 pm
OLAP Product: TM1 / Cognos Express
Version: PAL 2.0.9.1
Excel Version: 2016

VBA ‘Evaluate’ function generates an ‘Error 2015’

I am trying to check the value on a report has not changed since the report was generated. To do this I have the calculation in Excel set to manual and I am comparing the current value of the DBRW formula with the value contained withing the formula’s cell. I am using Excel 2003.

I have one specific DBRW that In the cell works every time — returning a decimal number. I am then using VBA to evaulate this formula by using the ‘Application.Evaluate’ function — in order to compare the result of the DBRW with the cell value.

Every time I do this I reveive an ‘Error 2015’ or ‘Type mismatch’ error.

I am returning the result into a variant object — so there can be no ‘type mismatch’ on the part of the variable I am loading the result of the ‘Evaluate’ into.
I have tried restarting Excel (in case this is some kind of ‘Caching’ issue) to no effect.

I am aware of the issue with ‘Evaluate’ where one or more parameters has 255 or more characters or the result of the function is a string in excess of 255 characters. However I know this is not the case in this instance.

http://dutchgemini.wordpress.com/2009/0 … excel-vba/

I had the VBA stop before the ‘Evaluate’ is executed and evaluated each parameter seperatly by hand — none return an error and each is a valid and correct parameter value for the DBRW. This is not supprising since in the worksheet the cell formula evaulates without an error every time. However if I print the formula text to the debug window and then, with the code paused, manually execute the ‘Evaluate’ this fails with the same messsage.

One thought I did have is that two of the parameters / dimension elements resolve to what can loosely be refrered to as dates i.e. one is a month ‘MAR’ and one is a year ‘2012’. I have seen a MS article where Evaluate functions that include dates can be an issue but it does not appear to apply in this situation and it is for an older version of Excel.

http://support.microsoft.com/kb/211601

Theoretically (assuming the formula evaluates in the worksheet) there should be no issue whatsoever with the following type of function call

Code: Select all

dim varResult as variant
dim rngTargetCell as range

...
' Code to set rngTargetCell
...

varResult = Application.Evaluate(rngTargetCell.formula)

Of course the workaround is to simply parse the formula string to get the DBRW parameters and then manually execute in VBA via an ‘Application.Run’ call — but I would really like to know what such a basic function falls over with this error as the parameters of the DBRW are all valid.

lotsaram

MVP
Posts: 3615
Joined: Fri Mar 13, 2009 11:14 am
OLAP Product: TableManager1
Version: PA 2.0.x
Excel Version: Office 365
Location: Switzerland

Re: VBA ‘Evaluate’ function generates an ‘Error 2015’

Post

by lotsaram » Mon Mar 05, 2012 1:14 pm

Welcome to the forum Alastair,

Basic stuff maybe but you have checked that you are connected to the server before trying to evaluate the DBRW function?

AlastairFM wrote:Of course the workaround is to simply parse the formula string to get the DBRW parameters and then manually execute in VBA via an ‘Application.Run’ call — but I would really like to know what such a basic function falls over with this error as the parameters of the DBRW are all valid.

Another workaround would be to copy the sheet (or just the array of cells to be evaluated) elsewhere in Excel and paste as values then refresh the original area and compare values directly. Seems to me to be easier than parsing the DBRW formula arguments.

Out of interest what is the requirement behind comparing the current cube value vs. the value in the sheet. Surely what is relevant is the current value?

AlastairFM

Posts: 10
Joined: Mon Feb 28, 2011 12:13 pm
OLAP Product: TM1 / Cognos Express
Version: PAL 2.0.9.1
Excel Version: 2016

Re: VBA ‘Evaluate’ function generates an ‘Error 2015’

Post

by AlastairFM » Tue Mar 06, 2012 11:56 am

Sorry lotsaram obviously my previous reply to you wasn’t commited for some reason.

Yes I have checked all the basic stuff such as an active connection, the user is logged in and I have the correct security privillages. Although as it works ‘in cell’ in the same session these basic requirements would all have to be satisfied anyway.

Yes a workaround would be to copy the formula to another sheet, calculate and compare the two values but I already have found a workaround — I was just posting to see if anyone had encountered similar errors with the ‘Evalute’ function.

To explain what the requirement is, further to my origional post, I have to explain that this is a component of a reporting function is part of a very extensive VBA system that sits on the top of TM1. Each generated report can have functions performed on it’s values but not necessarly in the same session as the report was created. This taken in addition to the fact that another user could update / modify the underlying cube data requres us to run a check to make sure the cube cell value is the same as the report cell value before the function is initiated.

I am currently at a lost to explain why a function which works in cell and whose parameters are all valid when seperatly evaluated would fail. Even with the code paused at the failling point I can perform an evaluate on a basic TM1 formula such as below and have a valid return

Code: Select all


dim strFormula as string

strFormula = "=DIMNM(""myserver:}cubes"",1)"

msgbox Application.Evaluate(strFormula)

User avatar

Steve Rowe

Site Admin
Posts: 2344
Joined: Wed May 14, 2008 4:25 pm
OLAP Product: TM1
Version: TM1 v6,v7,v8,v9,v10,v11+PAW
Excel Version: Nearly all of them

Re: VBA ‘Evaluate’ function generates an ‘Error 2015’

Post

by Steve Rowe » Tue Mar 06, 2012 12:34 pm

It may be what you are seeing is pacularity of the DBRW function and I’d guess that your approach will work if you use a DBR?

The DBRW takes two goes to get it’s results the first «pass» sends the arguements to the server and the second «pass» gets the results. I think on the first pass the value of the formula is an error (#Value, not 100% sure) and this maybe what you are getting back in your evaluate function?

Seems plausible anyway….

lotsaram

MVP
Posts: 3615
Joined: Fri Mar 13, 2009 11:14 am
OLAP Product: TableManager1
Version: PA 2.0.x
Excel Version: Office 365
Location: Switzerland

Re: VBA ‘Evaluate’ function generates an ‘Error 2015’

Post

by lotsaram » Tue Mar 06, 2012 12:37 pm

I wouldn’t be that surprised by different behavior between stepping through VBA code versus what happens during runtime execution. Disappointed yes, frustrated certainly, but not surprised. I have been caught out too many times by such quirks where stepping through is OK but there are runtime errors (or the reverse for that matter).

AlastairFM

Posts: 10
Joined: Mon Feb 28, 2011 12:13 pm
OLAP Product: TM1 / Cognos Express
Version: PAL 2.0.9.1
Excel Version: 2016

Re: VBA ‘Evaluate’ function generates an ‘Error 2015’

Post

by AlastairFM » Tue Mar 06, 2012 12:46 pm

Yes that certainly does seem like a plausable explanation.

I have, however, setup the same system (TM1 server + VBA system + same OS ) in a virtual machine and that statement does not error. If your suggestion is correct Steve I would expect it to happen all the time.

I am wondering if this is somehow enviromental. Knowing Excel of old it has a problem when it comes to interpriting cells that it thinks are dates — and with the MS article in mind I am wondering if the client’s system is somehow differently configured. This may be supported by the fact that the client tested the system on another machine (of the same specification) and the error did not occur.

rmackenzie

MVP
Posts: 733
Joined: Wed May 14, 2008 11:06 pm

Re: VBA ‘Evaluate’ function generates an ‘Error 2015’

Post

by rmackenzie » Tue Mar 06, 2012 12:59 pm

I would second what the other guys said regarding the peculiarities of the DBRW and the Excel event model, but then again, you also said:

AlastairFM wrote:One thought I did have is that two of the parameters / dimension elements resolve to what can loosely be refrered to as dates i.e. one is a month ‘MAR’ and one is a year ‘2012’. I have seen a MS article where Evaluate functions that include dates can be an issue but it does not appear to apply in this situation and it is for an older version of Excel.

Interestingly, the blogger you referenced makes a further post regarding the shortcomings of Application.Evaluate. The stated issue sounds much more like the real problem you are facing — he states «I was less happy with the fact that Application.Evaluate() does not support or return all the data types.»

Of course the workaround is to simply parse the formula string to get the DBRW parameters and then manually execute in VBA via an ‘Application.Run’ call — but I would really like to know what such a basic function falls over with this error as the parameters of the DBRW are all valid.

IMO the Evaluate function isn’t a ‘basic’ function and has a lot of complexities — which makes life difficult for Excel developers who cannot be expected to anticipate the quirks of every third-party add-in that comes along. I’d agree with your own proposed solution which is to put the Run «DBRW», etc in a function. Also, if I might say, it sounds like you could also do something a bit more robust, on the TM1 side and not Excel, for reports to understand if the reporting model has changed since the last time the report was accessed and then act accordingly. If your model is updated via regular TIs then you could have a cube cell somewhere that had a measure ‘Last data update time’ (or similar) that would indicate if the data was fresh.

Finally, I don’t know if you are aware that TM1 has a very limited range of data-types compared to Excel. A cube cell can either contain a TM1 real or a TM1 string. There are other data types but cubes store only 2 types; a real is like a VB double and a string is a string. So, you don’t need to define the ‘result’ as a Variant, and you may be better advised to dimension it is either a double or string depending on what you expect and then there will be less ambiguity to code around.

Robin Mackenzie

rmackenzie

MVP
Posts: 733
Joined: Wed May 14, 2008 11:06 pm

Re: VBA ‘Evaluate’ function generates an ‘Error 2015’

Post

by rmackenzie » Tue Mar 06, 2012 1:13 pm

I see the thread moved on whilst I was typing… so I wonder what would happen if you did something like this:

Code: Select all

Dim strFormula as String

strFormula = "=DBRW(""myserver:}mycube"",""hardcoded element 1"",""hard coded element 2"",""etc"")"

MsgBox Application.Evaluate(strFormula)

This would pin down Evaluate’s approach to argument-type-conversion as the guilty party.

Robin

Robin Mackenzie

AlastairFM

Posts: 10
Joined: Mon Feb 28, 2011 12:13 pm
OLAP Product: TM1 / Cognos Express
Version: PAL 2.0.9.1
Excel Version: 2016

Re: VBA ‘Evaluate’ function generates an ‘Error 2015’

Post

by AlastairFM » Tue Mar 06, 2012 1:35 pm

Thank you rmackenzie for all you comments.

To answer your last question ; specifying the DBRW arguments as string literals works every time — which is why I suspected that Excel was ‘misundertanding’ the data types when it evaluated the formula. I do know about the limits to TM1’s datatypes and Excels. I am of the camp that absolutly hates the use of variants in code a) becuase they take more memory b) becuase they suggest poor design, in that you have not clearly defined and planned what datatype is to be returned by / used in a function. I am using it here to try and ensure there cannot be a ‘type mismatch’ due to the returned type being different from that which was expected.

I have to say I only ever use ‘Evaluate’ (or rather the shorthand version) to easily return the value or named ranges — although in general I am from the ‘old school’ of software development that gives all object refereces fully qualified names (that way there is less chance for errors). I

A UDF was my first instinct but for the sake of time this ‘seemed’ an easy compramise — evaluate the cells formula and compare it to the cells value. When I reenable this check I will definatly be creating a reusable function to evaluate a DBRW. Clearly ‘Evaluate’ is a function to avoid when working with TM1.

Unfortunatly the entire ‘reporting’ side of the sytem is Excel based (effectivly re-creating DBRW spreadsheets) — so to try and use any TIs to verify this would be overkill.

Понравилась статья? Поделить с друзьями:
  • What is format as table in excel
  • What is formal and informal word
  • What is forecasting in excel
  • What is forecast in excel
  • What is footnotes in word