我最近使用visual basic studio开始使用.NET visual basic进行编程。我也在使用excel VBA制作一些宏。如果有人能回答我的问题,我会非常感激,如果答案很明显,我会道歉,我只是开始:
基本上,如果我在excel VBA中设置了一个变量,例如:
dim text as string
text = "hello world"
在Visual Basic中编程时是否可以使用该变量,并且在excel VBA宏中设置它时保留其值。
如果您需要澄清,请发表评论。
非常感谢。
SOLUTION:
好的,我在解决方案的帮助下成功解决了这个问题,在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
答案 0 :(得分:1)
访问另一个工作簿的VBA代码中的变量的一种方法是创建将这些值返回给您的函数。然后从其他应用程序中调用这些函数。
例如,让它成为Excel文件中带有宏的模块中的代码:
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上搜索.Net代码来处理Excel对象)并试一试