簡體   English   中英

VBA使用3條條件將行從一張紙復制到另一張紙

[英]VBA to copy rows from one sheet to another using 3 criteria

我正在嘗試使用VBA在一個工作簿“ Transactional Files”的工作表中進行搜索,並基於三個條件將其復制到工作簿“ Utilities”的工作表中。 第一個條件是,如果列A =“ PV”,第二個條件是,列M是否具有“公用事業-水”,“公用事業-電”或“公用事業氣體”,而第三個條件是,如果列AE尚未存在在工作表中,如果同時滿足三個條件,則復制並粘貼該行。

我找到了此模板,但不確定在哪里插入我的條件:

Sub copyRow()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim lastrowDest As Long, currowSrc As Long, currowDest As Long, lastrowSrc 
As Long
Dim critvalue1 As String

Set ws1 = Sheets("Sheet2")
Set ws2 = Sheets("Sheet1")

lastrowSrc = ws2.Range("AE" & Rows.Count).End(xlUp).Offset(1).Row - 1
lastrowDest = ws1.Range("AE" & Rows.Count).End(xlUp).Row

For currowSrc = 2 To lastrowSrc
critvalue1 = ws2.Range("E" & currowSrc).Value
ws2.Cells(6, 5).Value = critvalue1
For currowDest = 2 To lastrowDest
    If ws1.Range("E" & currowDest).Value = critvalue1 Then
       ws2.Rows(currowSrc).Copy Destination:=ws1.Range("A" & currowDest)
    End If
Next currowDest
Next currowSrc

 End Sub

謝謝!!!

您提供的示例代碼是從一張紙到另一張紙。 您要檢查一個工作簿中的一張工作表,而要檢查另一張工作簿中的另一張工作表。

因此,您必須打開該工作簿(完成后關閉它)。

然后,您將在工作表中逐行查找

Dim trx as workbook ' the other workbook (i.e. the other excel file). 
' trx is a vba variable that will hold the contents of the transactions excel file
' a workbook has sheets in it. 
dim sheet1 as worksheet, sheet2 as worksheet 
' these are two vba variables holding the two sheets we'll work on. 
dim criteria1 as boolean, criteria2 as boolean, criteria3 as boolean
' boolean variables can have the value of True or False only. 

' just for reading 
dim columnAindex as integer, columnMindex as integer, columnAEindex as integer

columnAindex = 1
columnMindex = Range("1M").column ' 13
columnAEindex = Range("AE").column ' yup, that number
set trx = Workbooks.open("trx.xlsx")
set sheet2 = trx.Sheets(1) ' or whatever sheet by index or name.

For Each myrow in Rows 
    criteria1 = (myrow.cells(1,columnAindex) = "PV') ' .cells(1,1) is columnA of current row
    m = myrow.cells(1, columnMindex) ' value in cell of this current row, at column M
    criteria2 = ( (m = this) or (m = that) or (m = theother) )
    ' if the value in AE is unique for each row, this will work:
    ' I got that from another question on stack overflow   
    ae = myrow.cells(1, columnAEindex) ' value in our row at column AE
    set trxAEcolumnRange = sheet2.Range("AE:AE")
    criteria3 = IsError(Application.Match(ae, trxAEcolumnRange, 0)) ' true if could not find a match to the value in our row's ae. 


    if criteria1 and criteria2 and criteria3 then copypasterow(myrow)
next 
trx.close()
end sub

sub CopyPasteRow(aRow)
    aRow.copy
    sheet2.range.end.paste ' no need for xlup because this is the next empty row after the data
end sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM