gpt4 book ai didi

Excel VBA 无法打开工作簿

转载 作者:行者123 更新时间:2023-12-02 09:31:54 26 4
gpt4 key购买 nike

首先:我使用的是 Excel 2007,但代码也必须适用于 Excel 2003。

我的问题如下:我需要访问不同工作簿中的单元格,该工作簿可能已关闭。在网上可以找到以下代码:

Function Foo()
Dim cell As Range
Dim wbk As Workbook
Set wbk = Workbooks.Open("correct absolute path")
' wbk is Nothing here so the next statement fails.
Set cell = wbk.Worksheets("Sheet1").Range("A1")
Foo = cell.Value
wbk.Close
End Function

遗憾的是,wbk 在 open 语句之后什么都没有(我很想提供更好的错误消息,但不知道如何做到这一点;我会为真正的 IDE 和有用的语言提供什么:/) 。绝对路径正确并指向有效的 Excel xlsx 文件。

此外,我认为执行此操作的最佳方法是“缓存”工作簿,而不是每次调用函数时都打开/关闭它?任何可能的问题(除了必须处理工作簿显然已经打开的情况之外)?

单步执行时的图像: debugging info

最佳答案

我可以重现这个问题。仅当我尝试将此代码粘贴到用户定义的函数中时,才会发生这种情况。

我相信这是设计使然(引用的是 XL 2003,但同样的事情发生在 XL 2010 上)

Using VBA keywords in custom functions

The number of VBA keywords you can use in custom functions is smaller than the number you can use in macros. Custom functions are not allowed to do anything other than return a value to a formula in a worksheet or to an expression used in another VBA macro or function. For example, custom functions cannot resize windows, edit a formula in a cell, or change the font, color, or pattern options for the text in a cell. If you include "action" code of this kind in a function procedure, the function returns the #VALUE! error.

http://office.microsoft.com/en-us/excel-help/creating-custom-functions-HA001111701.aspx

我发现的唯一解决方法是通过普通宏调用此类代码。比如选择要应用它的单元格,然后循环选择等等。

关于Excel VBA 无法打开工作簿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7693530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com