我想知道我做錯了什麼......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)...
不知道數組的上限如何是一個負值...任何幫助,將不勝感激。
嗯 - 這肯定是錯了我的文檔:如果我插入以下行: \t'MsgBox(「UBound:」&UBound(aData2())&「。LBound:」&LBound(aData1()))' 我得到UBound:-1。 LBound:0. – Vignesh
「必須真實的是UBound> = LBound。」 - 除非數組爲空,請參閱我的答案。 – Joe