获取Messagebox以提及特定列

时间:2013-06-14 12:14:13

标签: excel vba

我编写了一个简单的代码来突出显示Excel列中最后使用的行。事实是,我想让消息框提到有问题的列 - 是否可以这样做?例如,我在这里使用了A列,并希望消息框显示“A列中最后一个未使用的行是”,同样如果我将LR更改为B列,C等。


Sub lastrowcolumn()
Dim LR As Integer
   LR = Cells(Rows.Count, "A").End(xlUp).Row
   Outcome = MsgBox("The last non-used row in column is" & " " & LR)
End Sub

2 个答案:

答案 0 :(得分:1)

要获取工作表上的最后一行或列,您可以随时执行Sheet.UsedRange.Rows.Count或Sheet.UsedRange.Columns.Count

您可以这样获取某个单元格或范围的列:

Split(Columns(Cells(1, 30).Column).Address(False, False), ":")

单元格的列:

Sub Example()
    Dim LR As Long
    Dim Col() As String

    LR = Cells(Rows.Count, "A").End(xlUp).Row
    Col = Split(Columns(Cells(1, 30).Column).Address(False, False), ":")
    MsgBox ("The last non-used cell is in column " & Col(0) & " row " & LR)
End Sub

范围列:

Sub Example()
    Dim LR As Long
    Dim Col() As String

    LR = Cells(Rows.Count, "A").End(xlUp).Row
    Col = Split(Columns(Range("A:C").Columns.Count).Address(False, False), ":")
    MsgBox ("The last non-used cell is in column " & Col(0) & " row " & LR)
End Sub

工作表中的最后一列:

Sub Example()
    Dim LR As Long
    Dim Col() As String

    LR = Cells(Rows.Count, "A").End(xlUp).Row
    Col = Split(Columns(ActiveSheet.UsedRange.Columns.Count).Address(False, False), ":")
    MsgBox ("The last non-used cell is in column " & Col(0) & " row " & LR)
End Sub

- 编辑 -

上次未使用的列:

Sub Example()
    Dim LR As Long
    Dim Col() As String

    LR = Cells(Rows.Count, "A").End(xlUp).Row
    'Col = Split(Columns(ActiveSheet.UsedRange.Columns.Count + 1).Address(False, False), ":")
    'Alternative method to get column number
    Col = Split(Columns(ActiveSheet.Columns.Count).End(xlToLeft).Address(False, False), ":")
    MsgBox ("The last non-used cell is in column " & Col(0) & " row " & LR)
End Sub

上次未使用的行:

Sub Example()
    Dim LR As Long
    Dim Col() As String

    LR = ActiveSheet.UsedRange.Rows.Count + 1
    Col = Split(Columns(ActiveSheet.UsedRange.Columns.Count + 1).Address(False, False), ":")
    MsgBox ("The last non-used cell is in column " & Col(0) & " row " & LR)
End Sub

答案 1 :(得分:0)

Option Explicit
Option Base 0

Private Const c_lVeryLastRow As Long = 1048577

'Worksheet_SelectionChange event
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim lFirstUnusedRow As Long

    lFirstUnusedRow = ActiveSheet.Range(Target.Address).End(xlDown).Row + 1
    If lFirstUnusedRow = c_lVeryLastRow Then
        If (Target.Value = "") Then
            lFirstUnusedRow = ActiveSheet.Range(Target.Address).End(xlUp).Row + 1 'Target.Row
        Else
            lFirstUnusedRow = Target.Row + 1
        End If
    End If
    Call MsgBox(CStr(lFirstUnusedRow))
End Sub