简体   繁体   English

VBA:复制并粘贴,然后搜索,复制并粘贴

[英]VBA: Copy & Paste, Then Search, Copy & Paste

I need your help please!! 我需要你的帮助! :O Currently I have an excel workbook with a macro that is able to do a search to locate the cell with the value and select the entire row. :O当前,我有一个带有宏的excel工作簿,该宏能够进行搜索以找到具有该值的单元格并选择整行。 After which it will copy & paste the row to a spreadsheet called "Search". 之后,它将复制该行并将其粘贴到名为“搜索”的电子表格中。

However, I need to alter the macro to copy & paste a fixed number of column header rows eg row 1 to 4 to the spreadsheet ("Search") before performing the search, copy & paste into the same spreadsheet ("Search"). 但是,我需要更改宏以在执行搜索之前将固定数量的列标题行(例如第1至4行)复制并粘贴到电子表格(“搜索”),然后复制并粘贴到同一电子表格(“搜索”)中。

Can anyone advise me how to do it? 谁能告诉我该怎么做? I was thinking of either doing it like this (select, copy and paste THEN search, select, copy and paste) or selecting multiple range eg (select row 1 to 4 AND the row identified after the search). 我正在考虑这样做(选择,复制并粘贴然后搜索,选择,复制并粘贴)或选择多个范围,例如(选择第1至4行以及搜索后确定的行)。

    Sub SearchForString()

Dim LSearchRow As Integer
Dim LCopyToRow As Integer
Dim LSearchValue As String

On Error GoTo Err_Execute

LSearchValue = InputBox("Please enter the staff ID.", "Enter value")

'Start search in row 5
LSearchRow = 6

'Start copying data to row 5 in Sheet1 (row counter variable)
LCopyToRow = 5

While Len(Range("A" & CStr(LSearchRow)).Value) > 0

  'If value in column A = LSearchValue, copy entire row to Sheet1
  If Range("A" & CStr(LSearchRow)).Value = LSearchValue Then

     'Select row in Sheet1 to copy
     Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
     Selection.Copy

     'Paste row into Sheet1 in next row
     Sheets("Search").Select
     Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
     ActiveSheet.Paste

     'Move counter to next row
     LCopyToRow = LCopyToRow + 1

     'Go back to Sheet1 to continue searching
     Sheets("Search").Select

  End If

  LSearchRow = LSearchRow + 1

Wend

'Position on cell A3
Application.CutCopyMode = False
Range("A3").Select



Exit Sub

 Err_Execute:
  MsgBox "An error occurred."

End Sub

This is my first answer which simply tidies up your existing code. 这是我的第一个答案,它只是整理您现有的代码。 All my changes and additions are marked with "quote hash". 我所有的更改和添加都用“ quote hash”标记。 Study the changes I have made and try to understand why I have made them. 研究我所做的更改,并尝试了解为什么要进行更改。 I plan two further answers. 我计划另外两个答案。

Option Explicit         '# Always include this statement at top
Sub SearchForString()

  Dim LSearchRow As Long        '# Integer creates 16-bit value which requires
  Dim LCopyToRow As Long        '# special processing on post-16-bit computers
  Dim LSearchValue As String

  Dim WshtSrc As Worksheet      '# Faster and more convenient if you are
  Dim WshtDest As Worksheet     '# working with more than one worksheet

  Set WshtSrc = Worksheets("Search")  '# These are probably the wrong
  Set WshtDest = Worksheets("Dest")   '# worksheet names

  '# I never use "On Error GoTo label" while developing macros because I want to
  '# know where an error occurs. Before release, I check for every condition that
  '# might lead to an error if possible.  If I cannot stop the possibility of an
  '# error, I will use "On Error Goto Next" and "On Error GoTo 0" either side of
  '# a problem statement and I will then test Err.  This will allows me to issue a
  '# useful message to the user even if I cannot do better.
  '# On Error GoTo Err_Execute

  LSearchValue = InputBox("Please enter the staff ID.", "Enter value")

  'Start search in row 5
  LSearchRow = 6

  'Start copying data to row 5 in Sheet1 (row counter variable)
  LCopyToRow = 5

  With WshtSrc

    While Len(.Range("A" & CStr(LSearchRow)).Value) > 0                 '#

      'If value in column A = LSearchValue, copy entire row to Sheet1
      If .Range("A" & CStr(LSearchRow)).Value = LSearchValue Then       '#

      .Rows(LSearchRow).Copy Destination:=WshtDest.Cells(LCopyToRow, 1)

        '# 'Select row in Sheet1 to copy
        '# Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
        '# Selection.Copy

        '# 'Paste row into Sheet1 in next row
        '# Sheets("Search").Select
        '# Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
        '# ActiveSheet.Paste

        'Move counter to next row
        LCopyToRow = LCopyToRow + 1

        '# 'Go back to Sheet1 to continue searching
        '# Sheets("Search").Select

      End If

      LSearchRow = LSearchRow + 1

    Wend

    'Position on cell A3
    'Range("A3").Select

  End With

  Exit Sub

'# Err_Execute:
'#    MsgBox "An error occurred."

End Sub

Answer 2 答案2

After LSearchValue = InputBox("Please enter the staff ID.", "Enter value") add: LSearchValue = InputBox("Please enter the staff ID.", "Enter value")添加:

  If LSearchValue = "" Or LSearchValue = "Enter value" Then
    ' User does not want to make a selection
    Exit Sub
  End If

  WshtDest.Cells.EntireRow.Delete

  '# Copy heading rows
  WshtSrc.Rows("1:4").Copy Destination:=WshtDest.Range("A1")

I should have included the first five lines in the first answer. 我应该在第一个答案中包含前五行。 Always give the user the means of saying: "Bother! I did not mean to do that" and getting out of the selection they have made. 总是让用户说:“兄弟!我不是故意这样做的”,并摆脱他们所做的选择。 I should have cleared the destination sheet of the previous selection before starting the new one. 在开始新选择之前,我应该已经清除了先前选择的目标表。

The final statement is the easiest way I know of copying four rows. 最后的陈述是我知道复制四行的最简单方法。

I have noticed an error in my first answer. 我在第一个答案中发现一个错误。 I missed two necessary changes: 我错过了两个必要的更改:

    While Len(.Range("A" & CStr(LSearchRow)).Value) > 0

      If .Range("A" & CStr(LSearchRow)).Value = LSearchValue Then

I omitted the periods in front of Range. 我省略了Range前面的句点。 Range operates on the active worksheet. Range在活动工作表上运行。 .Range operates on the worksheet specified in the With statement. .RangeWith语句中指定的工作表上运行。

Answer 3 答案3

I am not good on this issue so I'm the pot calling the kettle black. 我在这个问题上不好,所以我是把水壶叫黑的锅。 Use the power of Excel. 使用Excel的力量。 If Excel has a function that does what you want then use it. 如果Excel具有执行所需功能的功能,请使用它。

For my test data, I have four columns and my staff Ids are the letters A to D. To get the macro below, I: 对于我的测试数据,我有四列,我的员工ID是字母A到D。要获取下面的宏,我:

  • switched the macro recorder on 打开宏录制器
  • selected the first four columns 选择了前四列
  • selected AutoFilter to switch it on 选择自动过滤器将其打开
  • clicked the arrow at the top of column A and clicked value B 单击列A顶部的箭头,然后单击值B
  • selected AutoFilter to switch it off 选择自动过滤将其关闭
  • switched the macro recorder off 关闭宏录制器

.

Sub Macro2()
'
' Macro2 Macro
' Macro recorded 21/05/2014 by Tony Dallimore
'

'
    Columns("A:D").Select
    Selection.AutoFilter
    Selection.AutoFilter Field:=1, Criteria1:="B"
    Selection.AutoFilter
End Sub

Following the second AutoFilter statement, the screen was almost exactly what you want to copy if the user selects staff Id B. The "almost exactly" is because rows 2 to 4 are invisible. 在第二个AutoFilter语句之后,如果用户选择职员ID B,则该屏幕几乎就是您要复制的内容。“几乎完全”是因为第2至4行不可见。 If there is a way of telling AutoFilter you have four heading rows then I do not know it so I will fix that problem in a different way. 如果可以告诉自动筛选器您有四个标题行,那么我不知道,所以我将以另一种方式解决该问题。

The Macro Recorder does not know your objectives. 宏记录器不知道您的目标。 This code is syntactically correct but it is not good code so it will have to be tidied up. 该代码在语法上是正确的,但它不是很好的代码,因此必须进行整理。 Also, it does not copy the rows because I already know how to do that. 另外,它不会复制行,因为我已经知道该怎么做。 The macro below is smaller and if you have many rows, much faster. 下面的宏较小,如果您有很多行,则速度要快得多。

Sub SearchForString2()

  Dim LSearchValue As String

  Dim RngCopy As Range
  Dim RngData As Range

  Dim WshtSrc As Worksheet
  Dim WshtDest As Worksheet

  ' I should have included this in answer 1.  It stops the screen being repainted
  ' as the worksheets are changed which is both slow and irritating because of
  ' the flashing.
  Application.ScreenUpdating = False

  Set WshtSrc = Worksheets("Search")  '# These are probably the wrong
  Set WshtDest = Worksheets("Dest")   '# worksheet names

  LSearchValue = InputBox("Please enter the staff ID.", "Enter value")

  WshtDest.Cells.EntireRow.ClearContents

  If LSearchValue = "" Or LSearchValue = "Enter value" Then
    ' User does not want to make a selection
    Exit Sub
  End If

  With WshtSrc

    Set RngData = .Columns("A:D")   '   Change column range as necessary

    RngData.AutoFilter    ' Switch AutoFilter on.
    RngData.AutoFilter Field:=1, Criteria1:=LSearchValue
    .Rows("2:4").Hidden = False

    Set RngCopy = .Cells.SpecialCells(xlCellTypeVisible)

    RngCopy.Copy Destination:=WshtDest.Range("A1")

    RngData.AutoFilter ' Switch AutoFilter off.

  End With


  ' Note that there is no period before RngData or RngCopy.
  ' When you set a range, the worksheet is part of the range.
  ' So Columns is a "child" of WshtSrc but RngData and RngCopy are not.
  ' The following statement shows that RngData "knows" what worksheet
  'it applies to.

  Debug.Print "RngData's worksheet: " & RngData.Worksheet.Name

  Exit Sub

End Sub

You can use this code as you search code : 您可以在搜索代码时使用以下代码:

Selection.Find(What:=LSearchValue, After:=ActiveCell, LookIn:=xlValues, LookAt _
    :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    True, SearchFormat:=False).Activate
Dim valuerow As Integer
valuerow = Application.ActiveCell.Row  

valuerow is the row index of the found cell valuerow是找到的单元格的行索引

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

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