首页 > 解决方案 > 查找多次出现的文本(在工作表中查找最右边的字符串)并复制

问题描述

我想在 Sheet1 中找到文本“锁定”。

由于每周的销售数量被锁定,文本“锁定”将出现在第 3 行。前一周的将全部保留,因此我正在寻找代码以找到出现在第 3 行最右边的“锁定” 。

一旦检测到该单元格,我需要将选择偏移到第 5 行(同一列)并复制到表格底部。

然后需要将所选内容粘贴到单元格 M5 中。

如果需要更多信息,很乐意提供。

Columns(13).ClearContents

Cells.Find(What:="LOCKED", LookIn:=xlFormulas, LookAt _
:=xlPart, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Select

ActiveCell.Offset(2, 0).EntireColumn.Select
Selection.Copy
Columns(13).Select
ActiveSheet.Paste

标签: vbaexcel

解决方案


我相信以下将实现您想要的:

Sub foo()
Dim ws As Worksheet: Set ws = ActiveSheet
'declare and set the worksheet you are working with, amend as required
Dim rng As Range

ws.Columns(13).ClearContents
'clear contents of Column M

Set rng = ws.Rows("3:3").Find(What:="LOCKED", LookIn:=xlFormulas, LookAt _
:=xlPart, SearchDirection:=xlPrevious, MatchCase:=False, SearchFormat:=False)
'set the rng variable to the last "LOCKED" found in Row 3

If Not rng Is Nothing Then 'if found
    LastRow = ws.Cells(ws.Rows.Count, rng.Column).End(xlUp).Row
    'get the last row with data in that column
    ws.Range(ws.Cells(3, rng.Column), ws.Cells(LastRow, rng.Column)).Copy
    'copy from row 3 to last row in found column
    ws.Range("M5").PasteSpecial xlPasteAll
    'paste into Range M5
End If

Application.CutCopyMode = False
'Escape the copied range
End Sub

推荐阅读