Excel VBA错误1004-从VB.Net(Visual Studio)调用函数
我正在从VB.Net调用excel文件中的宏。每次我调用它,我都会在下面的代码行中得到一个错误1004Excel VBA错误1004-从VB.Net(Visual Studio)调用函数,excel,vba,vb.net,visual-studio,excel-addins,Excel,Vba,Vb.net,Visual Studio,Excel Addins,我正在从VB.Net调用excel文件中的宏。每次我调用它,我都会在下面的代码行中得到一个错误1004 Application.Run "ATPVBAEN.XLAM!Fourier", Sheets("Sheet2").Range("$Q$5:$Q$260"), _ Sheets("Sheet2").Range("$R$1:$R$256"), True, False 当直接从excel运行代码时,它工作得非常好。但是当它从VisualStudio运行时,就会发生错误 我通过在e
Application.Run "ATPVBAEN.XLAM!Fourier", Sheets("Sheet2").Range("$Q$5:$Q$260"), _
Sheets("Sheet2").Range("$R$1:$R$256"), True, False
当直接从excel运行代码时,它工作得非常好。但是当它从VisualStudio运行时,就会发生错误
我通过在excel中单击按钮和更改单元格使其工作,而这两种方法在VisualStudio中都不起作用。有人知道为什么会发生此错误。本文()中记录了此问题 下面演示参考文章中概述的方法。该示例包括空Catch块的使用。算了吧,这个例子只是演示加载addin工作簿的一种方法,而不是作为一篇关于如何遵循某人编程思想的论文
Sub DemoExcelAddinLoading()
Dim app As New Excel.Application
' you must have an open Workbook before trying to open the
' addin. if no Workbook is open, opening the addin will fail
Dim wb As Excel.Workbook = app.Workbooks.Open("path to your workbook")
' a big annoyance is that the addin seems to be loaded
' and installed if the current user-interactive Excel has it as such.
' this is useful to retrieve the addin file path though
Dim toolPakAddin As Excel.AddIn = Nothing
Try
' will throw if "Analysis ToolPak" not installed
toolPakAddin = app.AddIns("Analysis ToolPak")
Catch ex As Exception
End Try
Dim wbToolPak As Excel.Workbook = Nothing
If toolPakAddin IsNot Nothing Then
Try
wbToolPak = app.Workbooks.Open(toolPakAddin.FullName)
Catch ex As Exception
End Try
End If
If wbToolPak IsNot Nothing Then
' register the addin
Dim res As Boolean = app.RegisterXLL(toolPakAddin.Name)
' AutoRun macros are disabled under automation, so
' allow the addin to initialize
wbToolPak.RunAutoMacros(Excel.XlRunAutoMacro.xlAutoOpen)
End If
Dim rngIn As Excel.Range
Dim rngOut As Excel.Range
Dim ws As Excel._Worksheet = CType(wb.Worksheets("Sheet2"), Excel._Worksheet)
rngOut = ws.Range("$c$1:$c$8")
rngOut.Clear()
rngIn = ws.Range("$a$1:$a$8")
Dim wbName As String = wb.Name
app.Visible = True
Try
app.Run("ATPVBAEN.XLAM!Fourier", rngIn, rngOut, True, False)
Catch ex As Exception
End Try
' Note: do not attempt to close wbToolPak
wb.Saved = True
wb.Close()
app.Quit()
End Sub
如果你认为你可以复制VBA代码,把它粘贴到VB.NET中,它就会工作,我有个坏消息告诉你。。。首先,您需要声明什么是应用程序。在VBA中,它是宿主应用程序,在VisualStudio中,它应该是Excel对象,应该这样定义。这只是问题的一小部分。看看这篇文章——它解释了其中的一些想法。@Vityta,我不是在把VBA代码复制到VB。该代码位于Excel宏中。我在VB中所做的就是“oExcel.Run(MacroName)”这听起来更好。你能写一个吗?@vityta这个ATPVBAEN.XLAM是一个excel加载项。它是此操作“C:\Program Files(x86)\Microsoft Office\root\Office16\Library\Analysis”中的VBA分析包