在excel和visual basic之间共享variables

我最近开始使用Visual Basic Studio编程.NET visual basic。 我也使用Excel VBA来制作一些macros。 如果有人能回答我的问题,我会非常感激,如果答案很明显,我很抱歉,我刚刚开始:

基本上,如果我在Excel VBA中设置了一个variables,例如:

dim text as string text = "hello world" 

在Visual Basic中编程时,是否可以使用该variables,并保持其在Excel VBAmacros中的值。

请评论,如果你需要澄清。

非常感谢。

解:

好吧,我设法找出解决scheme的帮助下,VB中的代码如下:

 Imports Microsoft.Office.Interop.Excel Imports Microsoft.Office.Interop Imports Microsoft.Office.Core Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim oxl As excel.application Dim owb As excel.workbook Dim osheet As Excel.worksheet Dim orng As excel.Range Dim strtext As String oxl = CreateObject("Excel.application") owb = oxl.Workbooks.Open(Filename:="C:\Users\USERNAME\Documents\Variable Passing Test.xlsm") oxl.Run("dosomethingtostrtext") strtext = oxl.Run("getstrtext") MsgBox(strtext) End Sub End Class 

访问另一个工作簿的VBA代码中的variables的一种方法是创build函数,将这些值返回给您。 然后从你的其他应用程序调用这些function。

例如,让这个代码在你的Excel文件中的一个模块的macros中:

 Option Explicit Private strText As String ' Say you have a routine that manipulates strText (or not, even!) Public Sub doSomethingToSTRTEXT() strText = "Hello World!" End Sub ' This is the function to call to retrieve strText Public Function getSTRTEXT() As String getSTRTEXT = strText End Function 

这是其他地方的VBA项目代码(不在这台机器上运行.Net,只是微软办公室悲伤 ),你有这样的:

 Option Explicit Sub Test() ' Declare Dim WBK As Workbook ' Open the workbook in question Set WBK = Workbooks.Open(Filename:="C:\Path\To\File\With\VBA.xls") ' This code's own variable Dim strText As String ' Call the routine (or not) that does something to that workbook's vba's strText Application.Run (WBK.Name & "!doSomethingToSTRTEXT") ' Now let's retrieve that value via function! strText = Application.Run(WBK.Name & "!getSTRTEXT") ' Show it to me MsgBox strText End Sub 

我想离开上面的代码^转换成VB.Net给你(或者在SO上做一个search来处理.Net代码来处理Excel对象)并且试用它