我正在尝试根据条件将数据从一个excel工作簿复制到另一个工作簿。两个工作簿都有共同的EmpId列(第1列),我想将工资簿1的工资单(第2列)转移到第2工作簿中存在EmpId的员工的工作簿2的工作表1。
我写的代码是:
Dim varSheetA As Worksheet
Dim varSheetB As Worksheet
Dim i As Integer
Dim myData As Workbook
Set wbkA = Workbooks.Open(Filename:="Path of destination sheet")
Set varSheetA = Worksheets("Sheet1")
Set varSheetB = wbkA.Worksheets("Sheet1")
Set myData = wbkA
For i = 1 To 10
Dim j As Integer
For j = 1 To 10
If varSheetA.Cells(j, 1).Value = varSheetB.Cells(i, 1).Value Then
varSheetB.Cells(j, 2).Value = varSheetB.Cells(i, 2).Value
End If
Next j
Next i
myData.Save
我无法理解此代码中的问题。
答案 0 :(得分:2)
我认为问题出在这一行:
varSheetB.Cells(j, 2).Value = varSheetB.Cells(i, 2).Value
如果它是
会更有意义varSheetB.Cells(j, 2).Value = varSheetA.Cells(i, 2).Value
答案 1 :(得分:1)
当您打开工作簿时,此工作簿将成为活动工作簿。因此,当您设置varsheetA =工作表(“sheet1”)时,请参考wbkA的sheet1。
当你复制工资时,似乎也有对varsheetB的错误引用varsheetB.cells(j,2)= varsheetB.cells(i,2)不应该是varsheetB.cells(j,2)= varsheetA .cells(I,2)
试试这个
Dim varSheetA As Worksheet
Dim varSheetB As Worksheet
Dim i As Integer
Dim j As Integer
Dim myData As Workbook
Set varSheetA = ThisWorkbook.Worksheets("Sheet1")
Set wbka = Workbooks.Open(Filename:="d:\downloads\testsalary 2.xlsx")
Set varSheetB = wbka.Worksheets("Sheet1")
For i = 1 To 10
For j = 1 To 10
If varSheetB.Cells(i, 1).Value = varSheetA.Cells(j, 1).Value Then
varSheetB.Cells(i, 2).Value = varSheetA.Cells(j, 2).Value
Exit For
End If
Next j
Next i
wbka.Save