Excel VBA:为每个循环合并来自2个不同文件的行

时间:2011-10-18 17:41:40

标签: excel vba excel-vba

我有2个不同的Excel文件。我创建了第三个.xls文件,在那里我将编写宏。该宏需要检查第一个.xls文件中的所有记录的数据,并且应将每个记录与另一个.xls文件中的记录进行比较,如果它们匹配则;我应该将原始.xls文件中的所有记录复制到新的.xls文件中,并将新单元格添加到该记录中并附上信息。

在VBA中看起来应该是这样的:

SrcFile1 = path
SrcFile2 = path

for each record in src file1.sheet1
   temp valuecell=record.cell(B1)
   for each recordToCompare in srcfile2.sheet1
      temp valuecell2=recordToCompare.cell(B1)
      if(valuecell1==valuecell2) then
         ThisWorkbook.thisworksheet.activate
         valuecell2.copy
         add new cell = value valuecell1.range(A1)
   end for each
end for each

如果有人能给我一些提示或者只是一些帮助,我真的很感激!

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效,将其改变为你想要的方式:

SrcFile1 = "path"
SrcFile2 = "path2"

dim i as long
dim wkb1 as workbook, wkb2 as workbook
dim wks1 as worksheet, wks2 as worksheet
dim v1 as variant, v2 as variant

'Get workbooks
set wkb1=getobject(srcfile1)
set wkb2=getobject(srcfile2)
'Get worksheets
set wks1=wkb1.worksheets("Sheet1")
set wks2=wkb2.worksheets("Sheet1")
'Get data - transpose single column data so array will be one dimensional
v1=application.transpose(wks1.range("A1:A" & wks1.range("A65000").end(xlup).row))
v2=application.transpose(wks2.range("A1:A" & ubound(v1)))

for i=1 to ubound(v1)
  if v1(i)<> v2(i) then
    'Copy over different data, don't know how many columns you have, 
    ' you can also do a .end(xlleft) to get the last column
    wks2.range("A" & i & ":Q" & i)=wks1.range("A" & i & ":Q" & i)
    wks2.range("R" & i)= "Information here"
  end if
next i

您可以制作如下路径:“C:\ ExcelFileName.xls” 如果你要比较多列,那么你需要两个循环,我以为你只做一对一。所以你需要做这样的事情(我会让你为你的应用程序找出正确的逻辑):

dim j as long

v1=wks1.range(cells(1,1), cells(wks1.range("A65000").end(xlup).row _
   , wks.range("IV1").end(xlLeft))
v2=wks2.range(cells(1,1),cells(ubound(v1),ubound(v1,2))

for i=1 to ubound(v1)
  for j=1 to ubound(v1,2)
    if v1(i,j)<> v2(i,j) then
      wks2.range(cells(i,1),cells(i,ubound(v1,2))) _
           =wks1.range(cells(i,1),cells(i,ubound(v1,2)))
      wks2.range(cells(i,ubound(v1,2)+1))= "Information here"
      exit for