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

时间:2015-06-20 10:46:03

标签: excel vba excel-vba

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

代码:

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

1 个答案:

答案 0 :(得分:1)

正如加里的评论所指出的,你的问题不是很清楚,但是,我会试一试。

请注意:

Cells(...

在循环的每次迭代中计算j = Cells(Cells.Rows.Count, 2).End(xlUp).Row For i = 1 To j 表达式。如果选择在循环期间发生变化,那么它可以在每次迭代时给出不同的结果。我建议你这样做:

ab