Vba 在范围中使用动态行和列
有人能告诉我下面的代码哪里出错了吗Vba 在范围中使用动态行和列,vba,excel,Vba,Excel,有人能告诉我下面的代码哪里出错了吗 Dim lastcol as Long, endrow as Long lastcol = Cells(3, Column.Count).End(xlToLeft).Column endrw = Cells(Rows.Count, “B”).End(xlUp).Row Range(“D4:” & Cells(endrow, lastcol)).Select 这是导致“错误”的最后一行。 endrow查找第44行 lastcol找到N列这一行:范围(
Dim lastcol as Long, endrow as Long
lastcol = Cells(3, Column.Count).End(xlToLeft).Column
endrw = Cells(Rows.Count, “B”).End(xlUp).Row
Range(“D4:” & Cells(endrow, lastcol)).Select
这是导致“错误”的最后一行。
endrow查找第44行
lastcol找到N列这一行:范围(“D4:&Cells(endrow,lastcol))。选择
,更准确地说,这条语句将D4:&Cells(endrow,lastcol)
与Cells(endrow,lastcol)
的值连接在一起,所以它可能是任何东西(如果能形成有效范围,那将是非常幸运的:))
可以使用单元格或通过传递定义范围的字符串来指定范围,但两者不能像您那样混合(只要单元格不包含其他单元格地址)
所以你应该写:
范围(单元格(4,4),单元格(endrow,lastcol))。选择你的代码中有几个错误:
列-在第2行中
endrw-在第三排
通过字母或索引引用列
请尝试此变体:
Dim lastcol As Long, endrow As Long
lastcol = Cells(3, Columns.Count).End(xlToLeft).Column
endrw = Cells(Rows.Count, "B").End(xlUp).Row
Range(Cells(4, 4), Cells(endrw, lastcol)).Select
注;您将结束行变量声明为endrw
,然后将其用作endrow
,还编写了Column
,而不是Columns
在最后一行中,您尝试从预定义单元格(D4
)创建一个范围,并将其扩展到新标识的单元格。此时,您正试图将字符串“D4”
与单元格的Range对象连接起来。相反,尝试
Range("D4:" & Cells(endrow, lastcol).Address(RowAbsolute:=False, ColumnAbsolute:=False)).Select
甚至更好
Range(Cells(4,4), Cells(endrow, lastcol)).Select
第一个将新单元格转换为字符串地址,第二个仅使用D4
的范围对象(单元格)而不是字符串地址
总而言之,它应该是这样的
Sub Test()
Dim lastcol As Long, endrow As Long
lastcol = Cells(3, Columns.Count).End(xlToLeft).Column
endrow = Cells(Rows.Count, 2).End(xlUp).Row
Range(Cells(4, 4), Cells(endrow, lastcol)).Select
End Sub
您发布的代码包含“智能引号”-如果这些引号存在于实际代码中,则需要将其替换为“常规”引号。