从表中最后使用的列复制数据

时间:2019-09-15 09:28:44

标签: excel vba

enter image description here

您好,我有一个表格需要用上次使用的coluumn中的数据填充第一个空列。如图所示,Enq 2为空。我需要做的是找到第一个空列(我认为我在下面),然后从Enq 4中剪切数据,粘贴2,然后在4中删除数据。

Sub Test()

Dim cel As Range

Dim MyRange As Range
Set MyRange = ActiveSheet.ListObjects("Table1").HeaderRowRange.Offset(1, 0)
 For Each cel In MyRange.Cells
    If cel = "" Then
    MsgBox cel.Address
    End If
 Next cel
End Sub

谢谢

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

Sub Test()

    Dim iCol As Long, lastUsedColumn As Long

    With ActiveSheet.ListObjects("Table1") ' reference your table object

        For iCol = 1 To .ListColumns.Count ' loop through its columns
            If IsEmpty(.DataBodyRange(1, iCol)) Then ' if current column first row value is empty
                With .DataBodyRange(1, .ListColumns.Count) ' reference last column first row cell
                    If .Value = vbNullString Then 'if empty
                        lastUsedColumn = .End(xlToLeft).Column ' get excel sheet column index of preceeding first not empty cell in same row 
                    Else ' otehrwise
                        lastUsedColumn = .Column ' get its excel sheet column index
                    End If

                End With

                lastUsedColumn = lastUsedColumn - .DataBodyRange(1, 1).Column + 1 ' translate excel column index to table column index 
                Exit For
            End If
        Next

        If lastUsedColumn > 0 and lastUsedColumn > icol Then .ListColumns(iCol).Range.Value = .ListColumns(lastUsedColumn).Range.Value 

    End With
End Sub