在 Excel VBA 中清除所选单元格右侧的单元格 - 无法猜测列字母标题

在 Excel VBA 中清除所选单元格右侧的单元格 - 无法猜测列字母标题

我已经成功找到行和列的结尾,但我只能删除列而不能删除行。问题是行使用数字,但我的代码想要一个列字母。我的目标是删除右侧单元格 A5 之后的所有内容。有人能指点一下吗?

代码:

Sub Range_End_Method()
'Finds the last non-blank cell in a single row or column

Dim lRow As Long
    'Find the last non-blank cell in column A(1)
    lRow = Cells(Rows.Count, 1).End(xlUp).Row

With ActiveWorkbook.ActiveSheet.Range("A1:A" & lRow & "")
    .Clear
End With

Dim lCol As Long
    'Find the last non-blank cell in row 1
    lCol = Cells(1, Columns.Count).End(xlToLeft).Column

With ActiveWorkbook.ActiveSheet.Range("A1:???" & lCol & "")
   .Clear
End With

End Sub

答案1

更新:我知道有一种方法,但无法弄清楚,但 Ted.D 和 BusyByte 帮助我找到了方法,不将列号转换为字母。此代码更简单且有效:

Sub Clear()

Dim lCol As Long
    'Find the last non-blank cell in row 1
    lCol = Cells(1, Columns.Count).End(xlToLeft).Column
ActiveWorkbook.ActiveSheet.Range("E5", Cells(1, lCol )).Clear

End Sub

这将找到最后使用的列作为数字,然后将其转换为字母,然后删除右侧第一个硬编码单元格(最后使用的列)之后的所有单元格。

Function Col_Letter(lngCol As Long) As String
    Dim vArr
    vArr = Split(Cells(1, lngCol).Address(True, False), "$")
    Col_Letter = vArr(0)
End Function

Sub Range_End_Method()
Dim lCol As Long
    'Find the last non-blank cell in row 1
    'but returns a NUMBER, that's what function Col_Letter converts to Letter
    lCol = Cells(1, Columns.Count).End(xlToLeft).Column

With ActiveWorkbook.ActiveSheet.Range("A5:" & Col_Letter(lCol) & "1")
   .Clear
End With

End Sub

相关内容