将非空数组值粘贴到Excel中

我使用下面的代码来遍历一个数组(从一个范围填充),然后将该单元格的值添加到另一个数组,然后将新数组粘贴到Excel中的表中。 它工作正常,但它也粘贴到表中的所有空数组值,这是一个问题,因为我有一个下拉列表使用该表,它包含大量的空值在最后。

有没有办法,我可以从数组中删除空值或只粘贴非空的值?

Sub newFilterStaff() Dim sourceData, targetData() As Variant Dim sourceRange, targetRange, rng As Range Dim sheet As Worksheet Dim i, staffCount As Integer Dim time As Long Dim name As String time = GetTickCount 'Set default values staffCount = 0 Set sheet = Worksheets("wfm_staff") Set sourceRange = sheet.[C1:C100] sourceData = sourceRange.Value 'sheet.Range("E2:E50").Clear 'Clear previous list For i = LBound(sourceData, 1) To UBound(sourceData, 1) If sourceData(i, 1) <> "XXXX" And i <> 1 Then 'Remove header row Set rng = sheet.Range("A" & i) With rng name = .Value End With ReDim Preserve targetData(0 To staffCount) 'Add name to array targetData(staffCount) = name staffCount = staffCount + 1 End If Next Range("E2:E" & UBound(targetData) + 1) = WorksheetFunction.Transpose(targetData) Debug.Print GetTickCount - time, , "ms" End Sub 

然后检查空白:

 Sub newFilterStaff() Dim sourceData, targetData() As Variant Dim sourceRange, targetRange, rng As Range Dim sheet As Worksheet Dim i, staffCount As Integer Dim time As Long Dim name As String time = GetTickCount 'Set default values staffCount = 0 Set sheet = Worksheets("wfm_staff") Set sourceRange = sheet.[C1:C100] sourceData = sourceRange.Value 'sheet.Range("E2:E50").Clear 'Clear previous list For i = LBound(sourceData, 1) To UBound(sourceData, 1) If sourceData(i, 1) <> "XXXX" And i <> 1 Then 'Remove header row If sourceData(i, 1) <> "" Then Set rng = sheet.Range("A" & i) With rng name = .Value End With ReDim Preserve targetData(0 To staffCount) 'Add name to array targetData(staffCount) = name staffCount = staffCount + 1 End If End If Next Range("E2:E" & UBound(targetData) + 1) = WorksheetFunction.Transpose(targetData) Debug.Print GetTickCount - time, , "ms" End Sub 
 If name <> "" Then targetData(staffCount) = name staffCount = staffCount + 1 End If