I created a DLL containing a function called "koduj". Calling this function using it inside an Excel worksheet cell returns the desired result. Calling "koduj" from VBA returns an incorrect answer.
koduj needs two arguments: string nr_id and integer x1 . It calculates the sum of nr_id letters in the ASCII representation and adds x1 . The calculated amount is returned.
I found the following instructions here .
Here is my .cpp source file:
#include<Windows.h> #include<string> using namespace std; //Convert BSTR to wstring for convenience wstring BSTR_to_wstring (BSTR text){ return wstring(text, SysStringLen(text)); } //Calculate sum of letters in ASCII representation int ASCII_sum (wstring ws){ int sum = 0; for (unsigned int i = 0; i < ws.length(); i++) sum += ws[i]; return sum; } //"koduj" function int _stdcall koduj (BSTR nr_id, int & x1){ wstring ws_nr_id = BSTR_to_wstring(nr_id); return ASCII_sum(ws_nr_id) + x1; }
Here is my VBA function declaration:
Declare Function koduj _ Lib "<dll_directory_and_full_name>" (ByVal x As String, ByRef y As Integer) As Integer
We write:
=koduj("aaa";1)
Inside the sheet cell, I get the desired result (292)
Debugging this VBA code:
Sub test() Dim a As Integer a = koduj("aaa", 1) End Sub
shows an incorrect result (a = 24930)
I believe that my C ++ code is great, as it works correctly when called from an Excel worksheet.
source share