【发布时间】: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 参数。在我继续之前,我只想先让这部分工作。