【问题标题】:I need to use the lastrow in my range to create a code [duplicate]我需要使用我范围内的 lastrow 来创建代码 [重复]
【发布时间】:2022-01-28 02:49:45
【问题描述】:

我想创建一个按钮,打印出一系列单元格,但范围总是因行数而异。我想我可以使用 Lastrow 功能,所以每次需要打印时我都不需要手动调整代码。需要打印的 Range 是 B2:S50 但行号总是会改变,因此我认为 Lastrow 可以帮助我免于手动更改。

我尝试了以下代码:

Sub printproposal()

Sheets("Proposals").Activate


Dim Lastrow As Integer

Lastrow = Range("B" & Rows.Count).End(xlUp).Row
' MsgBox Lastrow


Range(Lastrow, "B"):("S2").Printout



Sheets("Proposals").Range(Cells(Lastrow, "B"), 
 Cells("S2")).printout



End Sub

【问题讨论】:

  • 试试Range("B" & LastRow & ":S2").Printout
  • 成功了!非常感谢!

标签: excel vba


【解决方案1】:

参考列范围

  • 当不知道哪一列的最后一个单元格有值时,可以使用RefColumns函数:
Option Explicit

Sub PrintProposal()
    
    Const wsName As String = "Proposals"
    Const Cols As String = "B:S"
    Const fRow As Long = 2

    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
    Dim frrg As Range: Set frrg = ws.Rows(fRow).Columns(Cols) ' "B2:S2"
    Dim rg As Range: Set rg = RefColumns(frrg) ' "B2:SLastRow"
    
    rg.PrintOut
    
End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Creates a reference to the range from the first row of a range
'               ('FirstRowRange') to the row range containing
'               the bottom-most non-empty cell in the row's columns.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefColumns( _
    ByVal FirstRowRange As Range) _
As Range
    If FirstRowRange Is Nothing Then Exit Function
    
    With FirstRowRange.Rows(1)
        Dim lCell As Range
        Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
            .Find("*", , xlFormulas, , xlByRows, xlPrevious)
        If lCell Is Nothing Then Exit Function ' empty range
        Set RefColumns = .Resize(lCell.Row - .Row + 1)
    End With

End Function

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
相关资源
最近更新 更多