繁体   English   中英

将包含指定行数据的最后一列复制到下一个空白列

[英]Copy last column with data on specified row to the next blank column

我有一个电子表格,我需要查找其中包含数据的最后一列。 然后,我需要复制此列并将其复制到下一个空白列。

有没有办法做到这一点?

我设法做到了使用行:

lastrowSrc = Sheets("Overview").Range("B" & Rows.Count).End(xlUp).Row

但是,这使B12处于使用column.count的范围内.count仅输入列号而不是字母

要获取工作表中的确切列,请使用此代码。

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim LastCol As Long

    Set ws = Sheets("Sheet1")

    '~~> This check is required else .FIND will give you error on an empty sheet
    If Application.WorksheetFunction.CountA(ws.Cells) = 0 Then
        LastCol = 1
    Else
        LastCol = ws.Cells.Find(What:="*", _
                After:=ws.Range("A1"), _
                Lookat:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByColumns, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False).Column
    End If

    Debug.Print LastCol
End Sub

编辑 :这是礼貌@brettdj。 您还可以使用范围对象找到最后一列

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim LastCol As Long
    Dim rng As Range

    Set ws = Sheets("Sheet1")

    Set rng = ws.Cells.Find(What:="*", _
                After:=ws.Range("A1"), _
                Lookat:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByColumns, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False)

    If rng Is Nothing Then
        LastCol = 1
    Else
        LastCol = rng.Column
    End If

    Debug.Print LastCol
End Sub

要获取特定行的最后一列,请说第1行使用此

    Debug.Print ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column

ws是您的相关工作表。

对于Row同样,请参见this

我发现某些答案不适用于我的工作表,该工作表的末尾几行比工作表中的其他行短。 提供的代码仅提供工作表最后一行的最后一列。 相反,我使用代码循环来查找行中的最后一列,并使用“查找”示例获取工作簿中的最后一行。

Sub Sample()
    Dim ws As Worksheet
    Dim CurrRow, RowLastCol, LastRow, LastCol As Long

    Set ws = Sheets("Sheet1")

    '~~> This check is required else .FIND will give you error on an empty sheet
    If Application.WorksheetFunction.CountA(ws.Cells) = 0 Then
        LastCol = 1
    Else
        LastCol = 0
        LastRow = ws.Cells.Find(What:="*", _
                After:=ws.Range("A1"), _
                Lookat:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False).Row
        ' Loop through all the rows of the sheet saving off the highest column count
        For CurrRow = 1 to LastRow
            RowLastCol = ws.Cells(CurrRow, Columns.Count).End(xlToLeft).Column
            If RowLastCol > LastCol Then
                LastCol = RowLastCol
            End If
        Next CurrRow
    End If

    Debug.Print LastCol
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM