在Excel中查找,剪切并将整行粘贴到另一个工作表

时间:2018-01-03 20:36:45

标签: excel-vba vba excel

我正在尝试从一张Excel工作表中查找,剪切并粘贴整行到另一张工作表,然后删除第一张工作表中的空白行。另外,如果找不到条件值,我需要一个消息框。我对下面的代码有两个问题:

  1. 如果在A列中找到该值,则在复制和粘贴发生之前,代码会尝试打开一个我必须取消取消的新工作簿
  2. 如果在A列中找不到该值,则代码会多次创建消息框。非常感谢任何帮助。
  3. 代码就在这里:

    select um.usrmst_name 'ITAM Owner',
           wg.workgrp_name 'TIDAL Workgroup',
           ISNULL(jm.jobmst_prntname, '') + '\' + jm.jobmst_name,
           -- left(isnull(jm.jobmst_prntname, '') + '\' + jm.jobmst_name, len(isnull(jm.jobmst_prntname, '') + '\' + jm.jobmst_name) - charindex('\',reverse(isnull(jm.jobmst_prntname, '') + '\' + jm.jobmst_name))) 'Job Group',
           right((isnull(jm.jobmst_prntname, '') + '\' + jm.jobmst_name), charindex('\', reverse(isnull(jm.jobmst_prntname, '') + '\' + jm.jobmst_name)) -1) 'Job'
           from jobmst jm
    inner join workgrp wg on wg.workgrp_id = jm.jobmst_owner
    inner join usrmst um on um.usrmst_id = wg.workgrp_owner
    where jm.jobmst_active = 'Y'
      and jm.jobmst_dirty != 'X'
      and um.usrmst_domain = 'ITAM'
      and (isnull(jm.jobmst_prntname, '') + '\' + jm.jobmst_name like '\%\%')
    

1 个答案:

答案 0 :(得分:0)

这应该做你需要的。注意我的评论。

Sub Allocate()

    Application.ScreenUpdating = False

    Dim checkSheet As Worksheet
    Set checkSheet = ThisWorkbook.Worksheets("mySheet") 'change to needed name

    Dim loanNumber As String
    loanNumber = Worksheets("AMode").Range("C2").Value

    If Not checkSheet.UsedRange.Columns(1).Find(loanNumber, lookat:=xlWhole) Is Nothing Then

        Dim usdRows As Long
        usdRows = checkSheet.Range("A1").CurrentRegion.Rows.Count

        Dim allocDev As Workbook
        Set allocDev = Application.Workbooks("allocations developments") 'assumes it's already open

        Dim i As Long
        For i = UsdRws To 2 Step -1

            If checkSheet.Range("A" & i).Value = loanNumber Then
                checkSheet.Rows(i).Copy allocDev.Sheets("AL").Range("A" & Rows.Count).End(xlUp).Offset(1)
                checkSheet.Rows(i).Delete
            End If

        Next

    Else

        MsgBox "Loan Number Not Found"

    End If

End Sub