VBA复制粘贴字符串搜索

时间:2015-05-06 19:05:04

标签: excel vba excel-vba

我似乎无法弄清楚如何编写一个通过单元格C10:G10搜索等于单元格A10的匹配的vba代码,一旦找到,将范围A14:A18复制到匹配的单元格但低于例如F14: F18(见图)

下面的宏

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

Attached image click here

4 个答案:

答案 0 :(得分:2)

试试这个:

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

编辑1:回答OP的评论

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

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

上面的代码找到与Cell A10完全相同的公式。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

另外另外的变种

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

答案 3 :(得分:0)

你走了,

    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