excel 使用变量& COUNTA选择范围

oalqel3c  于 2023-04-22  发布在  其他
关注(0)|答案(3)|浏览(136)

我想选择销售报表转储中的所有连续单元格。
该报告是一组列数(31)。尽管我想在代码中构建一些可变性,以适应列数的变化。
行数每周都在变化,有时更少,有时更多。它总是从单元格[ A4 ]开始。
我想使用COUNTA函数来计算使用的行数,然后将其设置为一个变量。类似于行数。
我明白
运行时错误“1004”:object '_Global的方法'Range'失败
对我来说,关键是学习VBA使用的任务,我需要得到的完成。我理解我的代码背后的逻辑。如果有人提出一个完全不同的代码,我可能会迷路。
但我思想开放。

Sub ReportArea()
    Dim numofrows As Integer
    Dim numofcols As Integer
    Dim mylastcell As String
    Dim myrange As Range
        
    Worksheets("Sheet1").Select
    numofrows = WorksheetFunction.CountA(Range("AE:AE"))
    numofcols = WorksheetFunction.CountA(Range("4:4"))
    Set myrange = Range(Cells(4, 1), Cells(numofrows, numofcols))
    Range(myrange).Select
End Sub
8cdiaqws

8cdiaqws1#

查找最后一行和最后一列

Sub Sht1Rng()
    Dim ws As Worksheet
    Dim numofrows As Long
    Dim numofcols As Long
    Dim myrange As Range
    Set ws = Sheets("Sheet1")
    With ws
        numofrows = .Cells(.Rows.Count, "AE").End(xlUp).Row
        numofcols = .Cells(4, .Columns.Count).End(xlToLeft).Column
        Set myrange = .Range(.Cells(4, 1), .Cells(numofrows, numofcols))
    End With
    MsgBox myrange.Address

End Sub

您也可以使用此代码。

Sub SelectLastCellInInSheet()
    Dim Rws As Long, Col As Integer, r As Range, fRng As Range
    Set r = Range("A1")
    Rws = Cells.Find(what:="*", after:=r, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    Col = Cells.Find(what:="*", after:=r, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    Set fRng = Range(Cells(2, 1), Cells(Rws, Col))    ' range A2 to last cell on sheet
    fRng.Select    'or whatever you want to do with the range
End Sub
zi8p0yeb

zi8p0yeb2#

除了我上面的评论,这是你正在尝试的吗?

Sub ReportArea()
    Dim ws As Worksheet
    Dim Lrow As Long
    Dim myrange As Range

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        '~~> Find Last row of COl AE. Change it to the relevant column
        Lrow = .Range("AE" & .Rows.Count).End(xlUp).Row

        Set myrange = .Range("A4:AE" & Lrow)

        With myrange
            '
            '~~> Do whatever you want to do with the range
            '
        End With
    End With
End Sub

注意:也不需要选择区域/工作表,直接使用对象即可。Interesting Read

iaqfqrcu

iaqfqrcu3#

已发布的替代解决方案:
1:

Dim LRow&, LColumn&
Lrow = Sheets("SheetName").Cells.SpecialCells(xlCellTypeLastCell).Row
LColumn = Sheets("SheetName").Cells.SpecialCells(xlCellTypeLastCell).Column
MsgBox "Last Row is: " & Lrow & ", Last Column is: " & LColumn

二:

Dim x As Range
Set x = Range(Split(Sheets("SheetName").UsedRange.Address(0, 0), ":")(1))
MsgBox "Last Row is: " & x.Row & ", Last Column is: " & x.Column

输出结果

相关问题