繁体   English   中英

VBA复制粘贴字符串搜索

[英]VBA Copy Paste string search

我似乎无法弄清楚如何编写一个在单元格C10:G10中搜索以找到等于单元格A10的匹配项的vba代码,一旦找到该匹配项,就将范围A14:A18复制到匹配的单元格中,但在下面,例如F14:F18(请参见图片)

下面的宏

'Copy
Range("A14:A18").Select
Selection.Copy
'Paste
Range("F14:F18").Select
ActiveSheet.Paste!

附图片点击这里

尝试这个:

With Sheets("SheetName") ' Change to your actual sheet name
    Dim r As Range: Set r = .Range("C10:G10").Find(.Range("A10").Value2, , , xlWhole)
    If Not r Is Nothing Then r.Offset(4, 0).Resize(5).Value2 = .Range("A14:A18").Value2
End With

范围对象具有Find Method来帮助您查找范围内的值。
然后返回与您的搜索条件匹配的Range对象。
要使值正确定位,只需使用Offset and Resize Method

Edit1:回答OP的评论

要在Ranges中查找公式,您需要将LookIn参数设置为xlFormulas

Set r = .Range("C10:G10").Find(What:=.Range("A10").Formula, _
                               LookIn:=xlFormulas, _
                               LookAt:=xlWhole)

上面的代码查找范围与单元格A10完全相同的范围。

Dim RangeToSearch As Range
Dim ValueToSearch
Dim RangeToCopy As Range
Set RangeToSearch = ActiveSheet.Range("C10:G10")
Set RangeToCopy = ActiveSheet.Range("A14:A18")

ValueToSearch = ActiveSheet.Cells(10, "A").Value
For Each cell In RangeToSearch
    If cell.Value = ValueToSearch Then
        RangeToCopy.Select
        Selection.Copy
        Range(ActiveSheet.Cells(14, cell.Column), _
            ActiveSheet.Cells(18, cell.Column)).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        Exit For
    End If
Next cell

另一种变体

1.使用For each循环

Sub test()
Dim Cl As Range, x&

For Each Cl In [C10:G10]
    If Cl.Value = [A10].Value Then
        x = Cl.Column: Exit For
    End If
Next Cl

If x = 0 Then
    MsgBox "'" & [A10].Value & "' has not been found in range 'C10:G10'!"
    Exit Sub
End If

Range(Cells(14, x), Cells(18, x)).Value = [A14:A18].Value

End Sub

2.使用Find方法(已由L42发布,但有所不同)

Sub test2()
Dim Cl As Range, x&

On Error Resume Next

x = [C10:G10].Find([A10].Value2, , , xlWhole).Column

If Err.Number > 0 Then
    MsgBox "'" & [A10].Value2 & "' has not been found in range 'C10:G10'!"
    Exit Sub
End If

[A14:A18].Copy Range(Cells(14, x), Cells(18, x))

End Sub

3,使用WorksheetFunction.Match

Sub test2()
Dim Cl As Range, x&

On Error Resume Next

x = WorksheetFunction.Match([A10], [C10:G10], 0) + 2

If Err.Number > 0 Then
    MsgBox "'" & [A10].Value2 & "' has not been found in range 'C10:G10'!"
    Exit Sub
End If

[A14:A18].Copy Range(Cells(14, x), Cells(18, x))

End Sub

干得好,

    Sub DoIt()
    Dim rng As Range, f As Range
    Dim Fr As Range, Crng As Range

    Set Fr = Range("A10")
    Set Crng = Range("A14:A18")
    Set rng = Range("C10:G19")
    Set f = rng.Find(what:=Fr, lookat:=xlWhole)

    If Not f Is Nothing Then
        Crng.Copy Cells(14, f.Column)
    Else: MsgBox "Not Found"
        Exit Sub
    End If
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM