创建宏以查找列中的最后8个数据点并重命名

时间:2013-07-26 16:41:04

标签: excel loops

我正在尝试创建一个宏,它允许我找到包含数据的最后8个单元格并重命名它们。我用它来找到最后一个单元格并重命名它。

ActiveSheet.Range("K65536").End(xlUp).Offset(0, 0).Select
ActiveCell.Name = "BackRho"

然后我需要转到接下来的8个数据点并重命名它们。问题是列并不总是满的,因此有时数据之间存在空白。我想我需要使用Is()为空但无法弄明白。

1 个答案:

答案 0 :(得分:1)

我相信这可以做你想要的:

Sub RenameLast8()
Dim ws As Excel.Worksheet
Dim SearchColumn As Excel.Range
Dim FoundCell As Excel.Range
Dim FirstAddr As String
Dim FoundCells As Long

Set ws = ActiveSheet
Set SearchColumn = ws.Range("K:K")
Set FoundCell = SearchColumn.Cells.Find(searchdirection:=XlSearchDirection.xlPrevious, what:="*", lookat:=xlPart)
If Not FoundCell Is Nothing Then
    FirstAddr = FoundCell.Address
    FoundCells = FoundCells + 1
    FoundCell.Name = "Name" & FoundCells
End If
Do Until FoundCell Is Nothing Or FoundCells = 8
    Set FoundCell = SearchColumn.Cells.FindPrevious(after:=FoundCell)
    If FoundCell.Address = FirstAddr Then
        Exit Do
    Else
        FoundCells = FoundCells + 1
        FoundCell.Name = "Name" & FoundCells
    End If
Loop
End Sub

如果发现少于8,则停止。

更改wsSearchColumn以适应。我不确定你的命名约定,所以只使用了“Name”和FoundCells索引。