Excel VBA – 使用variables&COUNTAselect范围

Excel VBA – 使用variables&COUNTAselect范围

垂涎VBA国王和皇后区,我试图学习Excel VBA。 一个简单的任务,我想要做的是select所有传染性细胞在我从销售收到的报告转储。 简单的我很确定,但是我是VBA的初学者。

好的报告信息:

报告是一个列数(31)。 尽pipe我想在代码中添加一些变化来适应列号的变化。

报告每周增加行数,less一些,有时甚至更多。 但总是从单元[ A4 ]开始。

我虽然使用COUNTA函数来计算使用的行数,然后将其设置为一个variables。 与行类似。

这是我想出来的,虽然我得到了“ 运行时错误'1004':object'_Global的方法'范围'失败…任何人都可以帮我”

对我来说关键是要学习使用我需要完成的任务的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 

PS我尝试阅读更简单的趋势,但只是被困惑的解决scheme,其中非常涉及。

查找最后一行和最后一列

 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 

collections本页http://www.xlorate.com/selection-codes.html

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

 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 

注意 :你也不需要select范围/工作表。 处理对象。 有趣的阅​​读

还有一个额外的select从我身边已经发布变种\

 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 

输出结果

在这里输入图像说明