我已經重寫這段代碼optimixe即速度:
- 檢測是否有E列條目前面使用
SpecialCells
立即返回使用變形公式的範圍和常量
- 陣列來處理列E的使用部分的每個區域(變量爲
X
),然後寫入單個二維輸出陣列Y
請注意,此代碼重新生成單元格中的值,無論它們是基於常量的公式。它可以很容易地更新,通過改變
X = rngArea.Value2
到X = rngArea.Formula
Y(lngRowTot) = rngArea.Value
返回公式Y(lngRowTot) = rngArea.Formula
樣本輸出
代碼
Sub GetEm()
Dim rng1 As Range
Dim rng2 As Range
Dim rngFinal As Range
Dim rngArea As Range
Dim X
Dim Y
Dim lngRow As Long
Dim lngRowTot As Long
'early exit if there are no values
If Application.CountA(Columns("E")) = 0 Then
MsgBox "Column E has no formulae or constants", vbCritical
Exit Sub
End If
'quickly determine the range of constants and formulae
On Error Resume Next
Set rng1 = Columns("E").SpecialCells(xlFormulas)
Set rng2 = Columns("E").SpecialCells(xlConstants)
On Error GoTo 0
If Not rng1 Is Nothing Then
If Not rng2 Is Nothing Then
Set rngFinal = Union(rng1, rng2)
Else
Set rngFinal = rng1
End If
Else
Set rngFinal = rng2
End If
ReDim Y(1 To 100)
'Look at each range area (data may not be continuous)
For Each rngArea In rngFinal.Areas
'Use variant arrays to popluate a single dimension string array
If rngArea.Cells.Count > 1 Then
X = rngArea.Value2
For lngRow = 1 To UBound(X)
lngRowTot = lngRowTot + 1
If lngRowTot Mod 100 = 0 Then ReDim Preserve Y(1 To (UBound(Y) + 100))
Y(lngRowTot) = X(lngRow, 1)
Next
Else
'handle single cells
lngRowTot = lngRowTot + 1
If lngRowTot Mod 100 = 0 Then ReDim Preserve Y(UBound(Y) + 100)
Y(lngRowTot) = rngArea.Value
End If
Next
'cut down array to require size
ReDim Preserve Y(1 To lngRowTot)
MsgBox Join(Y, ", "), , "Your array is"
End Sub
什麼樣的陣列,單維數字符串數組,二維數組等? E列中是否有公式單元格和/或常量(文本字符串或硬編碼數字)? – brettdj 2012-01-03 10:11:14
現在運行你的代碼(doh)罷工我的第一個問題....上面的代碼將運行在兩個公式/值和返回值(如我的代碼下面) – brettdj 2012-01-03 10:52:17