Excel VBA删除复制到工作表中的第一个单元格?

时间:2016-12-20 23:08:09

标签: excel vba excel-vba

我有一些代码可以将特定单元格复制到另一个工作表,每条新记录都会收到一个新行。它似乎在处理时正确复制了所有内容,因为我可以看到正确的单元格被复制到新工作表,包括A1。但是,完成此操作后,新工作表(A1)中的第一个单元格始终为空。 不知道这里出了什么问题,如果有人有任何想法/建议会很好吗?

提前致谢

Dim Countrows As Integer
Dim k As Integer
Dim serialid As String
Dim NextRow As Range
Dim backgrounddate As Date

Countrows = 0
'find last row in spreadsheet,
For k = 2 To Lastrow
    If IsEmpty(CallCalculate.Cells(k, 8)) = False Then

        Set NextRow = Range("A" & Countrows + 1)
        CallCalculate.Cells(k, 2).Copy

        BackgroundCalc.Activate
        NextRow.PasteSpecial Paste:=xlValues, Transpose:=False

        serialid = CallCalculate.Cells(k, 2)

        'add date
        Set NextRow = Range("B" & Countrows + 1)
        CallCalculate.Cells(k, 9).Copy

        BackgroundCalc.Activate
        NextRow.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Transpose:=False

        backgrounddate = CallCalculate.Cells(k, 9)
        Set NextRow = Nothing
        Countrows = Countrows + 1

    End If
Next k

1 个答案:

答案 0 :(得分:2)

当宏启动时CallCalculate处于活动状态时,您的第一个复制的单元格将被写入该表格(覆盖之前可能位于其单元格A1中的任何内容),而不是BackgroundCalc表。因此BackgroundCalc上的单元格A1在宏运行之前仍然没有变化(这可能是空白的)。

您的代码的重构版本(将同时修复错误)将是:

Dim Countrows As Integer
Dim k As Integer
Dim serialid As String
Dim backgrounddate As Date

Countrows = 0
'find last row in spreadsheet,
For k = 2 To Lastrow
    If Not IsEmpty(CallCalculate.Cells(k, "H")) Then
        Countrows = Countrows + 1

        serialid = CallCalculate.Cells(k, "B").Value
        BackgroundCalc.Cells(Countrows, "A").Value = serialid

        'add date
        backgrounddate = CDate(CallCalculate.Cells(k, "I").Value)
        BackgroundCalc.Cells(Countrows, "B").NumberFormat = CallCalculate.Cells(k, "I").NumberFormat
        BackgroundCalc.Cells(Countrows, "B").Value = backgrounddate
    End If
Next k