如何解决尝试在sheet1的最后一行的b列中查找单元格的值
我需要在sheet1的b列中找到最后一个单元格的值。该值将每周更改一次。然后,我想采用该值并在sheet2中找到它。然后,我要将所有低于此找到的值的数据复制并粘贴到sheet3。我无法使用下面的代码跳过第一部分:
Dim cell As Range
Dim rangefound As Integer
Dim lastRow As Long
lastRow = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row
Set cell = Range("B:B").Find("rangefound")
rangefound = lastRow = Cells(lastRow,2).Value
一个月来我一直在语法上苦苦挣扎,真的不知道自己在做什么。
解决方法
尝试
Sub test()
Dim cell As Range
Dim rangefound As Integer
Dim lastRow As Long
lastRow = Sheet1.Range("B" & Rows.Count).End(xlUp).Row
rangefound = Sheet1.Cells(lastRow,2).Value
Set cell = Sheet2.Range("B:B").Find(rangefound)
MsgBox "The value was found in Sheet2!" & cell.Address
End Sub
您的代码存在问题
- 使用
rangefound
之前没有一个值,即命令的顺序 - 使用
"rangefound"
作为文本而不是变量 - 错误的语法将值分配给
rangefound
- 不符合搜索条件的条件
编辑:要扩展代码以将找到的值以下的数据复制到另一张纸上,请使用“偏移量”引用下面的一行。有很多不同的方法可以做到这一点,因此使用“偏移”只是一种选择。
这是完整的代码
Sub test()
Dim mycell As Range,RangeToCopy As Range
Dim rangefound As Integer
Dim lastRow As Long
lastRow = Sheet1.Range("B" & Rows.Count).End(xlUp).Row
rangefound = Sheet1.Cells(lastRow,2).Value
' this is the cell with the found value
Set mycell = Sheet2.Range("B:B").Find(rangefound)
' now find the last row in Sheet2. We can use lastRow again,' since it is no longer needed elsewhere
lastRow = Sheet2.Range("B" & Rows.Count).End(xlUp).Row
' set the range to copy to start one cell below rangefound
' to the end of the data in column B
Set RangeToCopy = Sheet2.Range(cell.Offset(1,0),Sheet2.Cells(lastRow,"B"))
' copy the range and paste into Sheet3,starting at A1
RangeToCopy.Copy Sheet3.Range("A1")
End Sub
注意:我将变量名称从“ cell”更改为“ mycell”。最好使用不能被误认为Excel工件的变量名。
另一种编辑:如果需要粘贴到Sheet3的下一行中,请使用已经建立的技术。
[...]
Set RangeToCopy = Sheet2.Range(cell.Offset(1,"B"))
' get the next available row in Sheet3
lastRow = Sheet3.Range("A" & Rows.Count).End(xlUp).Row + 1
' copy and paste
RangeToCopy.Copy Sheet3.Range("A" & lastRow)
[...]
请注意,我将相同的变量用于三个不同的目的。如果这太令人困惑,请创建三个不同的变量。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。