在范围循环中删除空值

时间:2019-03-25 07:42:30

标签: excel vba

我想将一些数据从许多单个表过滤到1个表中。问题开始于我只想显示一些数据,而不是从looping.eg读取的所有值。我在A列中有很多数据。但是我只想选择很少的数据,并且此数据具有固定增量,例如A5,A10,A15列等。

我尝试使用if语句仅在有值但不起作用时进行选择,因为它会粘贴所有值。

Sub transpose1()

'***Define Variable
Dim Strings() As Variant
Dim n As Long
Dim LastRowData As Long
Dim LastRow As Long

'***Read Data
Sheets("Results").Activate
LastRow = Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
LastRowData = LastRow

'***Redefine Array
ReDim Strings(LastRowData)

'***Read Data Variable
For n = 2 To LastRowData 'loop strings data
    Strings(n) = Sheets("Results").Cells(1 + n, 1)
    n = n + 12 'data increment at fix size
Next n

'***Write data
If IsEmpty(n) = False Then 'select only n with value
    For n = 0 To LastRowData
            Sheets("Test Transpose").Cells(1 + n, 1) = Strings(n) ' paste value when only n has value only
    Next n
End If

End Sub

enter image description here

1 个答案:

答案 0 :(得分:1)

n是一个长变量,并且不为空。您应该检查strings(n)是否为空:

If Isempty(strings(n)) = False Then

此外,您还必须将此if语句放置在for循环内,否则它将每次都检查相同的元素:

For n = 0 to LastRowData    
    If Isempty(strings(n)) = False Then
          Sheets("Test Transpose").Cells(1 + n, 1) = Strings(n) ' paste value when only n has value only    
    End if  
Next n