Excel VBA - 使用变量&amp ;;选择范围COUNTA
Hi Staked VBA Kings&皇后区,我正在尝试学习Excel VBA。我想要做的一个简单任务是在我从sales获得的报表转储中选择所有传染性单元格。很简单,我确定,但我是VBA的初学者。
确定报告信息:
报告是一组设定的列(31)。虽然我想在我的代码中建立一些可变性以适应列数的变化。
报告每周按行数增加,有时减少,有时甚至更多。但始终从单元格[A4
]开始。
我使用COUNTA
函数来计算已使用的行数,然后将其设置为变量。与行类似。
这就是我想出来的,虽然我得到了一个" 运行时错误' 1004':方法'范围'对象' _Global失败......任何人都可以帮助我#34; 。
对我而言,关键是要使用我需要完成的任务来学习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
P.S我确实试过阅读更苗条的趋势,但只是把它当作非常复杂的解决方案而感到困惑。
答案 0 :(得分:1)
查找最后一行和最后一列
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
答案 1 :(得分:0)
继上面的评论之后,这是你在尝试的吗?
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
答案 2 :(得分:0)
我身边还有另外一个选项已发布变体\
Sub test()
Dim LRow&, LColumn
Lrow = Sheets("Sheet1").Cells.SpecialCells(xlCellTypeLastCell).Row
LColumn = Sheets("Sheet1").Cells.SpecialCells(xlCellTypeLastCell).Column
MsgBox "Last Row is: " & Lrow & ", Last Column is: " & LColumn
End Sub
输出结果