【问题标题】:VBA: Reference a sheet in another workbook that may or may not be closedVBA:引用另一个工作簿中可能会或可能不会关闭的工作表
【发布时间】:2016-10-27 22:02:29
【问题描述】:

请问有人可以帮我吗?我正在尝试引用另一个工作簿中的工作表,但该函数返回 #VALUE!错误。我认为这是导致错误的原因:

'Set variable for other Workbook
Dim oh As Workbook
'This filepath may need to be changed if the file is moved
Set oh = Workbooks.Open("C:\Filepath\Filename.xlsx")

'Set variable for cs sheet in the other workbook
Dim cs As Worksheet
Set cs = oh.Worksheets("cs")

完整的代码在这里:

Option Explicit

Function WLR(CN, Ct)

'Turn off screen updating
Application.ScreenUpdating = False

''Change this to refer to sheet in other workbook later.
''For now, it refers to the cs sheet on this workbook
'Dim cs As Worksheet
'Set cs = ThisWorkbook.Sheets("cs")

'Set variable for other Workbook
Dim oh As Workbook
'This filepath may need to be changed if the file is moved
Set oh = Workbooks.Open("C:\Filepath\Filename.xlsx")

'Set variable for cs sheet in the other workbook
Dim cs As Worksheet
Set cs = oh.Worksheets("cs")

'Get Info from cs sheet
Dim i As Integer
i = 2

With cs
    Do While i <= .Rows.Count 'Check you haven't exceeded the limit
        If .Cells(i, 2) <> "" Then 'Check the cell isn't blank
            If .Cells(i, 2) = CN Then 'Check if course name is in list
                Exit Do 'Exit loop with i set to correct row if CN is found
            End If
        Else
            WLR = "" 'Return blank if course name not found
            'Turn on screen updating
            Application.ScreenUpdating = True
            Exit Function
        End If
        i = i + 1
    Loop

'Turn on screen updating
Application.ScreenUpdating = True

'Set Result
WLR = .Cells(i, 6)

End With

End Function

我尝试将工作表复制到此工作簿,注释掉有关引用另一个工作表的部分并取消注释有关此工作簿中的 cs 工作表的部分,这很有效,但我真的需要它来引用另一个工作簿。有任何想法吗?我在这里搜索并尝试了很多东西,例如使用工作表索引,但我现在真的卡住了。

编辑:函数不会崩溃,它会返回 VALUE#!错误。我认为问题在于我尝试引用工作表的地方。我之前试过,只是引用工作簿,并没有返回错误。

【问题讨论】:

  • 你的目标是什么?返回对 Range 或 Range 值的引用?顺便说一句,您正在向函数传递未在其中使用的“Ct”参数
  • 我的目标是返回一个范围的值。我将以此为基础,将来将使用 Ct 参数。在我继续之前,我只想先让这部分工作。

标签: vba excel


【解决方案1】:

我认为你应该将你的函数定义为

Function WLR(CN, Ct) as string

【讨论】:

  • 我尝试了您的代码并尝试引用另一个工作簿。您的代码似乎工作正常。我可以获得#VALUE的唯一方法!错误值是单元格(i,6)包含#VALUE!错误本身。我正在使用 Excel 2013
  • 我也在使用 Excel 2013。当我尝试将工作表复制到同一个工作簿并且有效时,它也不能是单元格的内容。您是否修改了其他任何内容以使其正常工作?可能是因为我使用的是 Office 365?
  • 不@JeniD 除了文件名和位置之外,我没有在代码中附加任何内容。我不确定这是否是 Office 365 问题:(
  • 谢谢,那我在家试试。至少我知道我的第一段不是来自练习簿的 VBA 代码适用于某人:)
【解决方案2】:

知道了 - 事实证明您无法在函数中打开另一个工作簿,因此我在打开原始工作簿时在后台打开了另一个工作簿,然后在退出时不提示保存而将其关闭。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 2019-04-04
    • 2023-02-09
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    相关资源
    最近更新 更多