使用VBA从Excel复制/粘贴值时出现问题

我正在尝试读取源Excel文件并复制一些值并将其分配给目标工作表中的不同单元格。 但在macros执行后。 粘贴的价值并不如预期。

码:

Sub Import() Dim SourceFile As Workbook Dim SourceTab As Worksheet Dim TargetTab As Worksheet SourceFileName = Application.GetOpenFilename("Excel Files , *.xls;*.xlsx;*.csv") If SourceFileName = False Then Exit Sub Application.ScreenUpdating = False Set TargetTab = Sheets("Output") 'TargetRow = TargetTab.Cells(TargetTab.Cells.Rows.Count, 1).End(xlUp).Row + 1 TargetRow = 2 Set SourceFile = Workbooks.Open(SourceFileName) SourceFile.Activate Set SourceTab = Sheets("Input") SourceTab.Activate For i = 1 To Cells(Cells.Rows.Count, 2).End(xlUp).Row If SourceTab.Cells(i, 2) = "VS" Then TargetTab.Cells(i, 3).Value = SourceTab.Cells(i, 31).Value TargetTab.Cells(i, 5).Value = SourceTab.Cells(i, 11).Value TargetTab.Cells(i, 6).Value = SourceTab.Cells(i, 19).Value TargetTab.Cells(i, 7).Value = SourceTab.Cells(i, 27).Value TargetTab.Cells(i, 5).Value = SourceTab.Cells(i, 4).Value TargetTab.Cells(i, 11).Value = SourceTab.Cells(4, 5).Value TargetTab.Cells(i, 13).Value = SourceTab.Cells(2, 25).Value TargetTab.Cells(i, 16).Value = SourceTab.Cells(i, 8).Value SourceTab.Cells(i, 3).Resize(1, 50).Copy ThisWorkbook.Activate TargetTab.Activate Cells(TargetRow, 2).Select Selection.PasteSpecial Paste:=xlPasteValues Application.CutCopyMode = False SourceFile.Activate TargetRow = TargetRow + 1 'TargetNewRows = TargetNewRows + 1 End If Next SourceFile.Close False Application.ScreenUpdating = True MsgBox "Done" End Sub 

正如加里的评论所指出的那样,你的问题不是很清楚,但是,我会给它一个机会。

请注意,在:

 For i = 1 To Cells(Cells.Rows.Count, 2).End(xlUp).Row 

Cells(...expression式在循环的每次迭代都会被计算,如果循环中的select发生变化,那么每次迭代都会给出不同的结果,我build议你这样做:

 j = Cells(Cells.Rows.Count, 2).End(xlUp).Row For i = 1 To j