如何使用vba查找上次使用的列的地址

时间:2012-10-03 10:11:57

标签: vba excel-vba excel

  

可能重复:
  Last not empty cell in row; Excel VBA
  Finding the number of non-blank columns in an Excel sheet using VBA

您好我已经写了一个vba代码来获取所选单元格(活动单元格)的地址。但我想要最后使用的列地址的地址,这里是我写的代码

Dim a As String
a = Split(ActiveCell.Address, "$")(1)
MsgBox a

它工作正常,但我想要最后使用的列的地址。就像我的值达到“AB”列我希望使用vba代码获取该地址。

1 个答案:

答案 0 :(得分:2)

喜欢这个吗?

Option Explicit

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

    '~~> Set this to the relevant sheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    '~~> Get the last used Column
    LastCol = LastColumn(ws)

    '~~> Return Column Name from Column Number
    a = Split(ws.Cells(, LastCol).Address, "$")(1)

    MsgBox a
End Sub

Public Function LastColumn(Optional wks As Worksheet) As Long
    If wks Is Nothing Then Set wks = ActiveSheet
    LastColumn = wks.Cells.Find(What:="*", _
                After:=wks.Range("A1"), _
                Lookat:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByColumns, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False).Column
End Function