我使用下面的代码循环遍历数组(从一个范围填充),然后将单元格的值添加到另一个数组,然后将新数组粘贴到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
答案 0 :(得分:1)
然后检查空白:
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
答案 1 :(得分:0)
If name <> "" Then
targetData(staffCount) = name
staffCount = staffCount + 1
End If