获取列名称
编码是
dim a,b as double a = application.workbookfuncation.counta(thisworkbook.sheets(1).Range("A:A")) b = ThisWorkbook.Sheets(1).Range("A1").CurrentRegion.Columns.Count
值得关注的是,我无法知道如何从“A1”select数据到列columnaddress(b)
& a
请build议如何解决?
你做错了。 这是find最后一行和最后一列的错误方法。 你可能想看到这个
我已经评论了代码,所以你不应该有一个问题的理解,但如果你仍然这样做,只是回发:)
这是你正在尝试? ( 未经testing )
Sub Sample() Dim ws As Worksheet Dim lastrow As Long, lastcol As Long Dim rng As Range '~~> Change this to the relevant sheet Set ws = ThisWorkbook.Sheets("Sheet1") With ws If Application.WorksheetFunction.CountA(.Cells) <> 0 Then '~~> Find Last Row lastrow = .Cells.Find(What:="*", _ After:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row '~~> Find Last Column lastcol = .Cells.Find(What:="*", _ After:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Column '~~> Construct your range here Set rng = .Range("A1:" & _ Split(Cells(, lastcol).Address, "$")(1) & lastrow) With rng ' '~~> Do whatever you want to do with the range here ' End With End If End With End Sub
只要您知道它返回的内容,使用CurrentRegion
就没有任何问题。
它返回第1行和第1列定义的连续范围。
范围在第一行中第一个真空单元格左边的列的水平位置处结束。作为公式结果的零长度string不是真正的空白。
该范围在列A的第一个真空单元的正上方垂直结束。
如果A1是空的,A1的CurrentRegion是A1。
如果上述适合你的目的,那么你根本不需要你的例子中的variables。 您可以从A1到A1的当前区域的最后一行和一列获取地址,如下所示:
MsgBox ThisWorkbook.Sheets("Sheet1").[a1].CurrentRegion.Address
。
如果你想要一个对象variables,那么这样做:
Set r = ThisWorkbook.Sheets("Sheet1").[a1].CurrentRegion
现在整个范围用r
表示,你可以这样select它:
r.Parent.Activate r.Select
注意:如果在除了[A1]之外的任何其他范围上使用CurrentRegion
,则它返回的定义更为复杂,因为它会在上面和左边查找连续的数据; [A1]没有这样的地方。
注意:如果您需要查找允许在第1行和/或第A列中真正为空的单元格的最后一行和第列,则CurrentRegion
不会达到所需的结果。 你需要使用查找。