2013-12-18 83 views
2

我將以下代碼拼湊在一起,以便修剪工作表中每個單元格的前導和尾隨空格。爲了保持表格屬性,我需要確保我不會弄亂標題行。當我運行這個時候,除了標題行外,所有東西都被刪除我究竟做錯了什麼?在Excel中輸出數組

這是我第一次處理數組。當我在沒有數組的情況下嘗試這個時,代碼會花費一些時間來讀取和重寫表單中的每個單元格。該陣列速度更快,我不明白如何使用它。

Dim arrData(), arrReturnData() As Variant 
Dim rng As Excel.Range 
Dim i, j, lRows, lCols As Long 

Set rng = ActiveSheet.UsedRange 
Set rng = rng.Offset(1, 0).Resize(rng.Rows.Count - 1) 'don't mess with the header row 
arrData = rng.Value 

lRows = rng.Rows.Count 
lCols = rng.Columns.Count 

ReDim arrData(1 To lRows, 1 To lCols) 
ReDim arrReturnData(1 To lRows, 1 To lCols) 

For j = 1 To lCols 
    For i = 1 To lRows 
    arrReturnData(i, j) = Trim(arrData(i, j)) 
    Next i 
Next j 

rng.Value = arrReturnData 
Set rng = Nothing 

回答

4

要分配

arrData = rng.Value

然後redimming它。因此所有的價值都消失了。

順便說一句,你根本不需要ReDim arrData(1 To lRows, 1 To lCols)。將excel範圍存儲到變體數組時,數組會自動調整大小。

久經考驗

Option Explicit 

Sub Sample() 
    Dim arrData(), arrReturnData() As Variant 
    Dim rng As Excel.Range 
    Dim i, j, lRows, lCols As Long 

    Set rng = ActiveSheet.UsedRange 
    Set rng = rng.Offset(1, 0).Resize(rng.Rows.Count - 1) 

    lRows = rng.Rows.Count 
    lCols = rng.Columns.Count 

    ReDim arrReturnData(1 To lRows, 1 To lCols) 

    arrData = rng.Value 

    For j = 1 To lCols 
     For i = 1 To lRows 
      arrReturnData(i, j) = Trim(arrData(i, j)) 
     Next i 
    Next j 

    rng.Value = arrReturnData 
    Set rng = Nothing 
End Sub 
+0

在這種情況下,我會強烈建議[這](http://www.cpearson.com/excel/ArraysAndRanges.aspx)鏈接爲你 :) –

0

使用保留

Redim Preserve arrData(1 To lRows, 1 To lCols)