我正在从 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 运行代码时,它工作得很好。但是当它从 Visual Studio 运行时,就会出现错误。
我可以通过单击按钮和更改 Excel 中的单元格来实现它,但这两种方法在 Visual Studio 中都不起作用。有谁知道为什么会发生这个错误。
文章中记录了此问题在 Excel 中使用 CreateObject 命令时加载项不会加载(网络存档链接以防主链接失效)。
以下演示了参考文章中概述的方法。 该示例包括空 Catch 块 的使用。 克服它,这个例子只是为了演示加载插件工作簿的一种方法,并不意味着作为如何遵循某人的编程思想的论文。
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
这是一篇旧帖子,但我也有同样的问题。 我发现这篇文章非常有用: https://forum.excel-pratique.com/excel/macro-transformee-de-fourier-123780 它展示了如何在 Excel 中手动“激活”ATPVBAEN.XLAM, 或者如何通过脚本导入它