2013-04-18 67 views
3

我正在嘗試檢查工作簿中是否存在命名範圍,因爲我已經編寫了一個遍歷文件夾的迭代文件。我在下面寫的宏適用於'正常'命名範圍,但是當我將該函數的表名稱作爲命名範圍時失敗。Excel VBA - 如何檢查不同工作簿中表格的存在?

我在這裏和其他地方在互聯網上搜索了爲什麼這可能是這樣的,任何人都可以指出我(可能很明顯)做錯了?

任何幫助,將不勝感激!

感謝,

亞當

Public Function DoesNamedRangeExistInWorkbook(ByVal wb As Workbook, ByVal rangeName As String) As Boolean 

Const FN_NAME As String = "DoesNamedRangeExistInWorkbook" 
On Error GoTo catch 

    Dim rng As Range 
    Dim cellCount As Integer 

    Set rng = wb.Names(rangeName).RefersToRange 
    cellCount = rng.Cells.Count 
    DoesNamedRangeExistInWorkbook = True 

finally: 
    Set rng = Nothing 
    Exit Function 

catch: 
    Call ErrorReport(FN_NAME, False, Err.Number, Err.Description, rangeName & " could not be found in workbook: " & wb.Name) 
    DoesNamedRangeExistInWorkbook = False 
    Resume finally 

End Function 

回答

3

試試這個(UNTESTED

我假設表名也是該表否則你將不得不環路命名範圍通過表名來檢查它。讓我知道如果是這樣的話,我會更新代碼。

Public Function DoesNamedRangeExistInWorkbook(ByVal wb As Workbook, _ 
ByVal rangeName As String) As Boolean 
    On Error GoTo catch 

    Dim rng As Range 

    On Error Resume Next 
    Set rng = wb.Names(rangeName) 
    On Error GoTo 0 

    If Not rng is Nothing Then 
     DoesNamedRangeExistInWorkbook = True 
     Set rng = Nothing 
    Else 
     DoesNamedRangeExistInWorkbook = False 
    End If 

    Exit Function 
catch: 
    DoesNamedRangeExistInWorkbook = False 
End Function 

EDIT

下面是用於檢查是否在工作簿或不存在一個特定的表中的代碼。我們使用表名來檢查它的存在。這個代碼再次未經測試。

Public Function DoesTableExist(ByVal wb As Workbook, _ 
ByVal tblName As String) As Boolean 
    On Error GoTo catch 

    DoesTableExist = False 

    Dim lstobj As ListObject, ws As Worksheet 

    For Each ws In wb.Worksheets 
     For Each lstobj In ws.ListObjects 
      If lstobj.Name = tblName Then 
       DoesTableExist = True 
       Exit Function 
      End If 
     Next 
    Next 

    Exit Function 
catch: 
    DoesTableExist = False 
End Function 
+0

嗨Siddharth,謝謝你的回覆!我測試了你給出的第一個解決方案(如果可能,我想對'普通'命名範圍和表名進行相同的測試工作),我在'If Not rng = Nothing'上得到一個編譯錯誤'invalid use of object' '一旦編譯器達到功能就行? – AdamDynamic

+0

我的歉意。我只是直接輸入。將該行更改爲'If Not rng is Nothing Then' –

+1

我試着用'is'來代替,並得到與我最初的方法相同的問題。我試過你的第二個解決方案,但它的工作完美,再次感謝您的幫助! – AdamDynamic

相關問題