簡體   English   中英

VBA如何運行代碼,直到它到達最后一個max函數

[英]VBA how to run the code until it reaches the last max function

我有一個數組代碼,可以保存我的電子表格中D +到D列的所有數據,但是它也保存了我不想要的工作表中的所有空白單元格。 所有列都有相同的行數,但理想情況下我希望數組從第二行開始,直到找到它從列D開始的最后一次重復。我的代碼是:

Sub PopulatingArrayVariable()

Dim myArray() As Variant
Dim DataRange As Range
Dim cell As Range
Dim x As Long
Dim TotalTargets As Double

TotalTargets = WorksheetFunction.Max(Columns("D"))

Set DataRange = Sheets("Result").Range("D:I")

For Each cell In DataRange.Cells
    ReDim Preserve myArray(x)
    myArray(x) = cell.Value
    x = x + 1
Next cell
End Sub

這是一種替代方法,應該完全跳過ReDim Preserve

看看它是否有助於你的情況。

Sub BuildArray()
Dim lngLastRow As Long
Dim rng As Range
Dim arList As Object
Dim varOut As Variant

lngLastRow = Sheets("Result").Range("D:I").Find("*", Sheets("Result").Range("D1"), , , xlByRows, xlPrevious).Row
Set arList = CreateObject("System.Collections.ArrayList")
For Each rng In Sheets("Result").Range("D1:I" & lngLastRow)
    If Len(Trim(rng.Value)) > 0 Then
        arList.Add rng.Value
    End If
Next
varOut = arList.ToArray

End Sub

在添加到數組之前添加單元格長度的條件:

For Each cell In DataRange.Cells
    If Len(Trim(Cells)) > 0 Then
        ReDim Preserve myArray(x)
        myArray(x) = cell.Value
        x = x + 1
    End If
Next cell

Trim()將從左側和右側移除空格,因此如果只有一個像這樣的空間的單元格 它仍然會給0並且不會被考慮在內。

修剪MSDN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM