如何使用.Find和Offset调试VBA代码?

时间:2016-04-27 10:08:11

标签: excel vba excel-vba

我正在练习VBA,我需要一些帮助/纠正我的代码。 在此任务中,我创建了一个搜索工具,该工具从组合框中查找每个工作表中的选定值。每个结果都列在第一页上。

问题:

  1. 在代码中,我将.Find方法定义为范围rFound。在每个工作表上,搜索的值位于列D。我想将B列中的行复制到E。我已经评论过一次尝试如何尝试选择该范围,但是我收到错误。为什么以及如何解决这个问题?

  2. 当我想粘贴(列出)结果时,我希望它从第1页第3行列K开始。运行代码后,它会选择正确的目标,但不会粘贴任何内容。如何解决这个问题?

  3. 我还尝试在每次搜索结果后复制文档标题,但我对其进行了评论,请忽略getOwner行。

    Dim ws As Worksheet, OutputWs As Worksheet, wsLists As Worksheet
    Dim rFound As Range ', getOwner As Range
    Dim strName As String
    Dim count As Long, LastRow As Long
    Dim IsValueFound As Boolean
    'Dim cboSelectName As ComboBox
    Dim a As String
    
    
    IsValueFound = False
    Set OutputWs = Worksheets("Teszt")    '---->change the sheet name as required
    LastRow = OutputWs.Cells(Rows.count, "A").End(xlUp).Row
    Set wsLists = Worksheets("Lists")
    
    a = ComboBox1.Value
    
    On Error Resume Next
    strName = a
    If strName = "" Then Exit Sub
    For Each ws In Worksheets
        If ws.Name <> "Output" Then
            With ws.UsedRange
                Set rFound = .Find(What:=strName, After:=.Cells(1, 1), LookIn:=xlValues, LookAt:=xlWhole)
                If Not rFound Is Nothing Then
                    Application.Goto rFound, True
                    IsValueFound = True
                    'MsgBox rFound.Row
                    rFound.EntireRow.Copy
                    'Rfound keres - rFound.Range(rFound(Offset(-2,")),rFound.Offset(1,"")).Copy  ' ---> This is a suggestion
                    OutputWs.Cells(LastRow + 2, 11).PasteSpecial xlPasteAll
                    'getOwner.Range(K2, R2).Copy        ' attempt to copy the header for each search result
                    'getOwner.Cells(LastRow + 1, 6).Paste
                    Application.CutCopyMode = False
                    LastRow = LastRow + 1
                End If
            End With
        End If
    Next ws
    On Error GoTo 0
    If IsValueFound Then
       OutputWs.Select
       MsgBox "Search Complete!"
    Else
        MsgBox "Value not found"
    End If
    

1 个答案:

答案 0 :(得分:0)

您选择整行但是将其粘贴到K列。如果复制整行,则只能将其复制到A列。这就是它无效的原因。所以我建议你研究Offset部分。 在偏移中,第一部分是行,第二部分是列。 你可以做那样的事,

Dim sth as Range
set sth = .range(.rfound.offset(0,-2),.rfound.offset(0,1)).copy

但我不确定。不太好。