根据条件在Excel工作簿之间复制单元格值

时间:2019-05-30 21:51:47

标签: excel vba excel-vba macros

我有两个出色的工作簿,比如wb01和wb02。

我需要通过基于以下准则将它们从wb01复制到wb02来进行同步:当ID匹配时,名称和姓氏的单元格值必须从wb01复制到wb02。

示例

wb01


import serial 
import time 


def send_input(cmd,port):
    '''
    This function sends input to the native serial console. 
    Parameters:
    cmd: a str type, command.
    port: a pyserial pointer. 

    Returns:
    None 
    '''
    port.write(cmd.encode() + '\r'.encode())
    time.sleep(1) 
    port.readline()

def recieve_output(port):
    '''
    This reads the output data from the native serial console. 
    Parameters:
    port: a pyserial pointer. 

    Returns:
    None 
    '''
    print(port.read(port.inWaiting()).decode().strip('-->'))

def main():
    '''
    pySerial pointer is initialized, 
    continuous user prompt  until exit string 
    is passed in. 
    '''

    port = serial.Serial('/dev/cu.usbserial-A5343FPC') #connect to port 

    while True:
        usr_input = input('v:> ')

        if usr_input.lower() != 'exit':
            send_input(usr_input,port)
            recieve_output(port)

        else:
            print('Exiting Program')
            return 
main()

wb02

WWW www = new WWW(requestUrl);
yield return www;
onTextureLoaded(www.texture,id);

仅当ID匹配时,更改才从wb01到wb02沿一个方向进行。 另外,如果在wb01上存在ID,但在wb02中不存在ID,则应将名称和姓氏的单元格值复制到wb02作为新行,并且在wb02中将其余字段保留为空/空白。

同步后,wb02必须如下:

Id | name     | surname  | Dept
10 | John     | McCoy    | Logistics
21 | Liam     | Alloy    | Administration
40 | Peter    | Gregor   | Finance
42 | Albert   | Kein     | Business
50 | Kelly    | Braxton  | Logistics
60 | Isabella | O'Neill  | Finance

我希望仅在用户单击wb02上的工作表中的按钮时按需完成同步。在按钮上单击它将执行一个宏,以开始从wb01到wb02的同步过程。

1 个答案:

答案 0 :(得分:0)

您实际上没有提供尝试用来执行此操作的任何代码,如果您至少尝试进行编码,那么更多的人会很乐意为您提供帮助... 但是,您没有提供工作表名称,这是一些可以测试的代码。

Sub CopyValue

Dim Wb1 As Workbook, wb2 As Workbook, lastrow As Long, lastrow2 As Long, counter As Integer

counter = 0
Set wb1 = Workbooks("wb01")
Set wb2 = Workbooks("wb02")
lastrow = wb1.Range("A" & .Rows.Count).End(xlUp).Row
lastrow2 = wb2.Range("A" & .Rows.Count).End(xlUp).Row

For x = 2 To lastrow
    For y = 2 To lastrow2
    If wb1.Sheets("abc").Cells(x,1).Value = wb2.Sheets("def").Cells(y,1).Value Then
        wb2.Sheets("def").Cells(y,2).Value =    wb1.Sheets("abc").Cells(x,2).Value
        wb2.Sheets("def").Cells(y,3).Value =    wb1.Sheets("abc").Cells(x,3).Value
    Else
        counter= counter +1
        wb2.Sheets("def").Cells(lastrow+counter,1).Value = wb1.sheets("abc").Cells(x,1).Value
        wb2.Sheets("def").Cells(lastrow+counter,2).Value = wb1.sheets("abc").Cells(x,2).Value
        wb2.Sheets("def").Cells(lastrow+counter,3).Value = wb1.sheets("abc").Cells(x,3).Value
    End If
Next y
Next x
End Sub