VBA:引用可能关闭或不关闭的另一个工作簿中的工作表

时间:2016-06-25 10:57:28

标签: excel vba excel-vba

有人可以帮帮我吗?我试图引用另一个工作簿中的工作表,但该函数返回一个#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#!错误。我认为这个问题是我尝试引用表格的地方。我之前尝试过,只是引用了工作簿而没有返回错误。

2 个答案:

答案 0 :(得分:0)

我认为你应该将你的功能定义为

Function WLR(CN, Ct) as string

答案 1 :(得分:0)

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