2013-05-28 103 views
0

我想知道我做錯了什麼......VBA UBound函數返回一個負值

我有一個word文檔(Word 2010中)在其三個表打開。我想在VBA中測試基本的表格提取,並遵循指令http://msdn.microsoft.com/en-us/library/office/aa537149(v=office.11).aspx

Sub ExtractTableData() 
    Dim doc As Word.Document 
    Dim tbl As Word.Table 
    Dim rng As Word.Range 
    Dim sData As String 
    Dim aData1() As String 
    Dim aData2() As String 
    Dim aDataAll() As String 
    Dim nrRecs As Long 
    Dim nrFields As Long 
    Dim lRecs As Long 
    Dim lFields As Long 

    Set doc = ActiveDocument 
    Set tbl = doc.Tables(1) 
    Set rng = tbl.ConvertToText(Separator:=vbTab, _ 
     NestedTables:=False) 
    ' Pick up the delimited text into and put it into a string variable. 
    sData = rng.Text 
    ' Restore the original table. 
    doc.Undo 
    ' Strip off last paragraph mark. 
    sData = Mid(sData, 1, Len(sData) - 1) 
    ' Break up each table row into an array element. 
    aData1() = Split(sData, vbCr) 
    nrRecs = UBound(aData1()) 
    ' The messagebox below is for debugging purposes and tells you 
    ' how many rows are in the table. It is commented out but can 
    ' be used simply by uncommenting it. 
    'MsgBox "The table contained " & nrRecs + 1 & " rows" 
    'Process each row to break down the field information 
    'into another array. 
    For lRecs = LBound(aData1()) To nrRecs 
     aData2() = Split(aData1(lRecs), vbTab) 
     ' We need to do this only once! 
     If lRecs = LBound(aData1()) Then 
      nrFields = UBound(aData2()) 
      ReDim Preserve aDataAll(nrRecs, nrFields) 
     End If 
     ' Now bring the row and field information together 
     ' in a single, two-dimensional array. 
     For lFields = LBound(aData2()) To nrFields 
      aDataAll(lRecs, lFields) = aData2(j) 
     Next 
    Next 
End Sub 

我得到一個錯誤,在這條線:使用ReDim保留aDataAll(nrRecs,nrFields),這是由於 「nrFields」 被設定爲負值(-1)...

不知道數組的上限如何是一個負值...任何幫助,將不勝感激。

回答

1

我想通了 - 我試圖提取一個嵌套的表。我必須遍歷所有子表並單獨提取。此外,我必須在提取之前搜索並刪除^p以保留表格結構。

我弄明白了之後,我注意到MS代碼示例有一個錯誤:aData2(j)實際上應該是aData2(lFields)

希望這有助於其他一些新手!

0

雖然很怪異,但VARIANT SAFEARRAY有可能對任何維度具有負值較低的上限值。數組範圍是LBound(,維)到UBound(,維)。

必須真實的是UBound> = LBound。

要得到數組的大小,使用UBound函數 - LBOUND + 1

它曾經是約定在VBA代碼頂部使用Option Base聲明雖然,當然設置下限,即沒有影響第三方庫返回的數組。大多數民間曾經使用1作爲下限。

+0

嗯 - 這肯定是錯了我的文檔:如果我插入以下行: \t'MsgBox(「UBound:」&UBound(aData2())&「。LBound:」&LBound(aData1()))' 我得到UBound:-1。 LBound:0. – Vignesh

+0

「必須真實的是UBound> = LBound。」 - 除非數組爲空,請參閱我的答案。 – Joe

0

如果UBound爲-1且LBound = 0,則該數組爲空。

Dim EmptyArray() As String 
Dim s As String 
EmptyArray = Split("") 
Debug.Print (UBound(EmptyArray)) ' displays -1 
Debug.Print (LBound(EmptyArray)) ' displays 0 

在你的情況,我懷疑你需要跳過處理,如果數組爲空::您可以通過以下方式生成一個空數組

aData1 = Split(...) 
If (UBound(aData1) < LBound(aData1) Then 
    ' UBound is -1 and LBound is 0, array is empty, nothing to do 
Else 
    ' Array is non-empty, do your stuff 
End If