我如何在VB.NET中使用Excel函数

时间:2022-08-26 22:34:43

I am actually trying to use the Gamma_Inv function but to minimize the complexity of having lots of variables I will use the pi function instead as it illustrates my problem more simply.

我实际上是在尝试使用Gamma_Inv函数,但为了最大限度地减少拥有大量变量的复杂性,我将使用pi函数,因为它更简单地说明了我的问题。

my code is:

我的代码是:

Imports Microsoft.Office.Interop.Excel

Public Class LoadData

    Shared Sub Main(ByVal cmdArgs() As String)

        Dim fred As WorksheetFunction

        MsgBox(fred.Pi)

    End Sub

End Class

The error i am getting is:

我得到的错误是:

Variable 'fred' is used before it is assigned a value.

变量'fred'在赋值之前使用。

This sort of makes sense, but what should I set it to?

这种情况很有意义,但我应该将它设置为什么?

It won't let me use:

它不会让我使用:

MsgBox(WorksheetFunction.Pi)

I am guessing it wants me to open a spreadsheet but I only want to use the function and not Excel itself.

我猜它要我打开一个电子表格,但我只想使用该功能,而不是Excel本身。

2 个解决方案

#1


3  

Yes, unfortunately you need a running Excel Application to use the Worksheet Functions.

是的,遗憾的是,您需要运行Excel应用程序才能使用工作表函数。

    Dim app = New Microsoft.Office.Interop.Excel.Application
    Dim wf = app.WorksheetFunction

    MsgBox(wf.Pi)
    MsgBox(app.Evaluate("PI()"))

    app.Visible = True ' optional
    app.Quit()         ' don't forget to close it when done !

The Evaluate method is a bit slower but can evaluate almost everything that can be used in the Excel Formula or Address Bar.

Evaluate方法有点慢,但几乎可以评估Excel公式或地址栏中可以使用的所有内容。

#2


1  

OK, I found the answer.

好的,我找到了答案。

You need to declare the application:

您需要声明应用程序:

    Dim value As New Application

then you can use the functions within it:

然后你可以使用其中的功能:

    MsgBox(value.WorksheetFunction.Pi)

#1


3  

Yes, unfortunately you need a running Excel Application to use the Worksheet Functions.

是的,遗憾的是,您需要运行Excel应用程序才能使用工作表函数。

    Dim app = New Microsoft.Office.Interop.Excel.Application
    Dim wf = app.WorksheetFunction

    MsgBox(wf.Pi)
    MsgBox(app.Evaluate("PI()"))

    app.Visible = True ' optional
    app.Quit()         ' don't forget to close it when done !

The Evaluate method is a bit slower but can evaluate almost everything that can be used in the Excel Formula or Address Bar.

Evaluate方法有点慢,但几乎可以评估Excel公式或地址栏中可以使用的所有内容。

#2


1  

OK, I found the answer.

好的,我找到了答案。

You need to declare the application:

您需要声明应用程序:

    Dim value As New Application

then you can use the functions within it:

然后你可以使用其中的功能:

    MsgBox(value.WorksheetFunction.Pi)