Hi, in the interest of keeping this brief, I've written a working example.
The VBA needs to be in a workbook that you open once your addin has been loaded, hence the theApp.WorkbookOpen event registration.
This code is not by any means robust, and only serves to help with showing how to use the VSTO. It lies to you to handle all errors correctly.
These techniques are all described in various blogs by authorities. I think Andrew Whitechapel has a blog on exposing com into VBA like this.
Lastly, this is only one technique, it's probably not the best, and it most certainly can be better written, I've just thrown the bits together to give you an example.
Regards
Some VBA
Option Explicit Public ComObject As Object Public Sub RegisterAddinCom(theComExposed As Object) Set ComObject = theComExposed End Sub Public Function ReturnTwo(ByRef theDest As Range) ReturnTwo = ComObject.ReturnTwo(theDest) End Function
RegisterInterest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; using System.Diagnostics; namespace ExamplesAndTestingExcelAddin { class RegisteredItem { public Excel.Range TheRange { get; set; } public object TheData { get; set; } } public class RegisterInterest { private static int iter; private Dictionary<string, RegisteredItem> _RegisteredItems; private Timer _Timer; public RegisterInterest() { iter = 0; _RegisteredItems = new Dictionary<string, RegisteredItem>(); _Timer = new Timer(); _Timer.Interval = Convert.ToInt16(TimeSpan.FromSeconds(10).TotalMilliseconds); _Timer.Start(); _Timer.Tick += new EventHandler(_Timer_Tick); } void _Timer_Tick(object sender, EventArgs e) { foreach (var RegisteredItems in _RegisteredItems) { try { RegisteredItems.Value.TheRange.Value2 = RegisteredItems.Value.TheData + " - " + iter.ToString(); } catch (Exception ex) { Debug.Print(ex.ToString()); } iter++; Debug.Print(RegisteredItems.Value.TheData + " - " + iter.ToString()); } } public void Add(Excel.Range rng,object data) { RegisteredItem regItem; string newAddress = rng.get_Address(false, false, Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1, false, false).ToString(); if (!_RegisteredItems.TryGetValue(newAddress, out regItem)) { _RegisteredItems.Add(newAddress, new RegisteredItem() { TheData = data, TheRange = rng }); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using Excel = Microsoft.Office.Interop.Excel; using Microsoft.Office.Interop.Excel.Extensions; namespace ExamplesAndTestingExcelAddin { [ComVisible(true)] public class ComExposed { private RegisterInterest _RegisteredInterest; public ComExposed() { _RegisteredInterest = new RegisterInterest(); } public string ReturnTwo(Excel.Range theDest) { _RegisteredInterest.Add(theDest,(string)theDest.Value2); return "Success"; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using Excel = Microsoft.Office.Interop.Excel; using Microsoft.Office.Interop.Excel.Extensions; using Office = Microsoft.Office.Core; namespace ExamplesAndTestingExcelAddin { public partial class ThisAddIn { private ComExposed _ComExposed; private void ThisAddIn_Startup(object sender, System.EventArgs e) { _ComExposed = new ComExposed(); Excel.Application theApp; theApp = this.Application as Excel.Application; theApp.WorkbookOpen += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookOpenEventHandler(theApp_WorkbookOpen); } void theApp_WorkbookOpen(Microsoft.Office.Interop.Excel.Workbook Wb) { Excel.Application theApp; theApp = this.Application as Excel.Application; theApp.Run("RegisterAddinCom", _ComExposed, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); } void theApp_SheetChange(object Sh, Microsoft.Office.Interop.Excel.Range Target) { } private void ThisAddIn_Shutdown(object sender, System.EventArgs e) { } #region VSTO generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InternalStartup() { this.Startup += new System.EventHandler(ThisAddIn_Startup); this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); } #endregion } }
A better method is to use Button's to fire off the population of the data to the sheet.
However addins like bloomberg and reuters both do what you are describing.
A trick, would be to include the destination cell of the datarange in your formula, and then on a timed event populate that range with your data after the udf has completed because excel is single threaded, You will then use your vsto to capture the address which you want to populate, and in a ontime event you could populate the range
public partial class ThisAddIn { private void ThisAddIn_Startup(object sender, System.EventArgs e) { GlobalEvent.TimeComplete += new GlobalEvent.GlobalEventDelegate(GlobalTimer_TimeComplete); } void GlobalTimer_TimeComplete(string message) { MessageBox.Show("You've done it"); } } <br/><br/><br/><br/><br/><br/>
public static class GlobalEvent { public delegate void GlobalEventDelegate(string message); public static event GlobalEventDelegate TimeComplete; public static void SetEvent(string message) { TimeComplete(message); } }
[ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class Functions { public double ReturnTwo() { GlobalEvent.SetEvent("me"); return 2; } [ComRegisterFunctionAttribute] public static void RegisterFunction(Type type) { Registry.ClassesRoot.CreateSubKey( GetSubKeyName(type, "Programmable")); RegistryKey key = Registry.ClassesRoot.OpenSubKey( GetSubKeyName(type, "InprocServer32"), true); key.SetValue("", System.Environment.SystemDirectory + @"\mscoree.dll", RegistryValueKind.String); } [ComUnregisterFunctionAttribute] public static void UnregisterFunction(Type type) { Registry.ClassesRoot.DeleteSubKey( GetSubKeyName(type, "Programmable"), false); } private static string GetSubKeyName(Type type, string subKeyName) { System.Text.StringBuilder s = new System.Text.StringBuilder(); s.Append(@"CLSID\{"); s.Append(type.GUID.ToString().ToUpper()); s.Append(@"}\"); s.Append(subKeyName); return s.ToString(); } } When I debug the code, the delegate seems to register with the event TimeComplete on the AddIn start up. However, when I run the UDF ReturnTwo() the debugger is telling me that TimeComplete is "null". I must be missing something crucial here as I don't understand how after I have set the event delegate (in the AddIn startup) it has been reset to null.using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Text; using System.Xml.Linq; using Excel = Microsoft.Office.Interop.Excel; using Office = Microsoft.Office.Core; using Microsoft.Office.Tools.Excel.Extensions; using System.Windows.Forms; using Data = System.Data; using System.Runtime.InteropServices; using Microsoft.Win32; using System.Diagnostics; using System.IO; namespace QuantAddIn { [ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public partial class ThisAddIn { public static List<string> RegisteredRanges = new List<string>(); private void ThisAddIn_Startup(object sender, System.EventArgs e) { Application.ActiveWorkbook.SheetChange += new Microsoft.Office.Interop.Excel.WorkbookEvents_SheetChangeEventHandler(ActiveWorkbook_SheetChange); } void ActiveWorkbook_SheetChange(object Sh, Microsoft.Office.Interop.Excel.Range Target) { } private void ThisAddIn_Shutdown(object sender, System.EventArgs e) { } #region VSTO generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InternalStartup() { this.Startup += new System.EventHandler(ThisAddIn_Startup); this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); } #endregion } [ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class Functions { public double ReturnTwo() { ThisAddIn.RegisteredRanges.Add("string"); return 2; } [ComRegisterFunctionAttribute] public static void RegisterFunction(Type type) { Registry.ClassesRoot.CreateSubKey( GetSubKeyName(type, "Programmable")); RegistryKey key = Registry.ClassesRoot.OpenSubKey( GetSubKeyName(type, "InprocServer32"), true); key.SetValue("", System.Environment.SystemDirectory + @"\mscoree.dll", RegistryValueKind.String); } [ComUnregisterFunctionAttribute] public static void UnregisterFunction(Type type) { Registry.ClassesRoot.DeleteSubKey( GetSubKeyName(type, "Programmable"), false); } private static string GetSubKeyName(Type type, string subKeyName) { System.Text.StringBuilder s = new System.Text.StringBuilder(); s.Append(@"CLSID\{"); s.Append(type.GUID.ToString().ToUpper()); s.Append(@"}\"); s.Append(subKeyName); return s.ToString(); } } }
Hi, in the interest of keeping this brief, I've written a working example.
The VBA needs to be in a workbook that you open once your addin has been loaded, hence the theApp.WorkbookOpen event registration.
This code is not by any means robust, and only serves to help with showing how to use the VSTO. It lies to you to handle all errors correctly.
These techniques are all described in various blogs by authorities. I think Andrew Whitechapel has a blog on exposing com into VBA like this.
Lastly, this is only one technique, it's probably not the best, and it most certainly can be better written, I've just thrown the bits together to give you an example.
Regards
Some VBA
Option Explicit Public ComObject As Object Public Sub RegisterAddinCom(theComExposed As Object) Set ComObject = theComExposed End Sub Public Function ReturnTwo(ByRef theDest As Range) ReturnTwo = ComObject.ReturnTwo(theDest) End Function
RegisterInterest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; using System.Diagnostics; namespace ExamplesAndTestingExcelAddin { class RegisteredItem { public Excel.Range TheRange { get; set; } public object TheData { get; set; } } public class RegisterInterest { private static int iter; private Dictionary<string, RegisteredItem> _RegisteredItems; private Timer _Timer; public RegisterInterest() { iter = 0; _RegisteredItems = new Dictionary<string, RegisteredItem>(); _Timer = new Timer(); _Timer.Interval = Convert.ToInt16(TimeSpan.FromSeconds(10).TotalMilliseconds); _Timer.Start(); _Timer.Tick += new EventHandler(_Timer_Tick); } void _Timer_Tick(object sender, EventArgs e) { foreach (var RegisteredItems in _RegisteredItems) { try { RegisteredItems.Value.TheRange.Value2 = RegisteredItems.Value.TheData + " - " + iter.ToString(); } catch (Exception ex) { Debug.Print(ex.ToString()); } iter++; Debug.Print(RegisteredItems.Value.TheData + " - " + iter.ToString()); } } public void Add(Excel.Range rng,object data) { RegisteredItem regItem; string newAddress = rng.get_Address(false, false, Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1, false, false).ToString(); if (!_RegisteredItems.TryGetValue(newAddress, out regItem)) { _RegisteredItems.Add(newAddress, new RegisteredItem() { TheData = data, TheRange = rng }); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using Excel = Microsoft.Office.Interop.Excel; using Microsoft.Office.Interop.Excel.Extensions; namespace ExamplesAndTestingExcelAddin { [ComVisible(true)] public class ComExposed { private RegisterInterest _RegisteredInterest; public ComExposed() { _RegisteredInterest = new RegisterInterest(); } public string ReturnTwo(Excel.Range theDest) { _RegisteredInterest.Add(theDest,(string)theDest.Value2); return "Success"; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using Excel = Microsoft.Office.Interop.Excel; using Microsoft.Office.Interop.Excel.Extensions; using Office = Microsoft.Office.Core; namespace ExamplesAndTestingExcelAddin { public partial class ThisAddIn { private ComExposed _ComExposed; private void ThisAddIn_Startup(object sender, System.EventArgs e) { _ComExposed = new ComExposed(); Excel.Application theApp; theApp = this.Application as Excel.Application; theApp.WorkbookOpen += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookOpenEventHandler(theApp_WorkbookOpen); } void theApp_WorkbookOpen(Microsoft.Office.Interop.Excel.Workbook Wb) { Excel.Application theApp; theApp = this.Application as Excel.Application; theApp.Run("RegisterAddinCom", _ComExposed, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); } void theApp_SheetChange(object Sh, Microsoft.Office.Interop.Excel.Range Target) { } private void ThisAddIn_Shutdown(object sender, System.EventArgs e) { } #region VSTO generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InternalStartup() { this.Startup += new System.EventHandler(ThisAddIn_Startup); this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); } #endregion } }
Tim Li
MSDN Subscriber Support in Forum
If you have any feedback on our support, please contact msdnmg@microsoft.com
聯(lián)系客服
微信登錄中...
請勿關(guān)閉此頁(yè)面
