[英]Not Able to Select a Range in Excel VBA
我已经在工作表“ A”中写了一个宏,
在工作表A更改时,我要从工作表“ C”复制一个范围并将其粘贴到工作表“ D”
这个流程很好,我能够实现。 问题是当我尝试在工作表B中选择范围时。
rownum= 83 (I get it dynamically)
colnum = 31 (Number of columns in rownum)
现在,我要将第83行复制到第31列。
问题开始:
Sheets("B").Range("A83:AO83").Select ~ works like Charm
由于上面不是动态的,我想用
Sheets("B").Range(Cells(rownum,1),Cells(rownum,colnum)).Select ~ Object Defined Error
有任何想法吗 !!! 我被卡了2个小时..没有发生。
这是代码的一部分,为了减少混乱,我并没有发布所有代码,代码在最后一行停止! 对象定义的错误。
Dim rownum As Integer
Dim colnum As Integer
rownum = Application.Match(searchFE, Sheets("Attendance").Range("D:D"), 0)
colnum = Cells(rownum, Columns.Count).End(xlToLeft).Column
Sheets("Attendance").Range(Cells(rownum, 1), Cells(rownum, colnum)).Select
rownum和colnum都在获取值。
让我们来看看
Sheets("Attendance").Range(Cells(rownum, 1), Cells(rownum, colnum)).Select
Cells(rownum, 1)
不完全合格。 没有明确给出应Sheet
获取Cells
。 因此假设使用ActiveSheet.Cells(rownum, 1)
。 因此,如果Sheets("Attendance")
不是活动工作表,则上述命令将失败。
...
With Sheets("Attendance")
.Range(.Cells(rownum, 1), .Cells(rownum, colnum)).Select
End With
...
我认为这只是.address
。 选择范围时,需要提供地址作为输入,因此基本上,您唯一的错误是写:
Sheets("B").Range(Cells(rownum,1),Cells(rownum,colnum)).Select
代替:
Sheets("B").Range(Cells(rownum,1).Address(0,0),Cells(rownum,colnum).Address(0,0)).Select
我喜欢写.address(0,0)
因为它提醒我它是绝对地址(从row和col = 0开始)
我也不确定:
Sheets("Attendance").Range(Cells(rownum, 1), Cells(rownum, colnum)).Select
通常我会写:
Worksheets("Attendance").Range(Cells(rownum, 1).address(0,0), Cells(rownum, colnum).address(0,0)).Select
如果要使用多个Workbook
,请小心参考特定的Workbook
!
如果要转到最后一行,请使用此代码
Sub GetThere()
Dim sh As Worksheet
Dim r As Long
Dim c As Long
Dim rng As Range
Set sh = Sheets("Attendance")
With sh
r = .Cells(.Rows.Count, "D").End(xlUp).Row
c = .Cells(r, .Columns.Count).End(xlToLeft).Column
Set rng = .Range(.Cells(r, 1), .Cells(r, c))
End With
Application.Goto Reference:=rng
End Sub
如果您实际上想对范围进行操作(例如将其复制到其他位置),请使用此代码。
Sub GetThere2()
Dim sh As Worksheet
Dim r As Long
Dim c As Long
Dim rng As Range
Set sh = Sheets("Attendance")
With sh
r = .Cells(.Rows.Count, "D").End(xlUp).Row
c = .Cells(r, .Columns.Count).End(xlToLeft).Column
Set rng = .Range(.Cells(r, 1), .Cells(r, c))
End With
rng.Copy Sheets("Sheet2").Range("A1")
End Sub
如果您确实要选择范围,则必须确保也选择了工作表。
Sub GetThere3()
Dim sh As Worksheet
Dim r As Long
Dim c As Long
Dim rng As Range
Set sh = Sheets("Attendance")
With sh
r = .Cells(.Rows.Count, "D").End(xlUp).Row
c = .Cells(r, .Columns.Count).End(xlToLeft).Column
Set rng = .Range(.Cells(r, 1), .Cells(r, c))
.Select
End With
rng.Select
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.