【问题标题】:Excel VBA deletes first cell copied into a sheet?Excel VBA删除复制到工作表中的第一个单元格?
【发布时间】:2016-12-20 23:08:09
【问题描述】:

我有一些代码可以将特定单元格复制到另一张纸上,每条新记录都会收到一个新行。它似乎在处理时正确复制了所有内容,因为我可以看到正确的单元格被复制到新工作表中,包括 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

【问题讨论】:

  • 很难猜。它不是来自此代码。也许触发了一些其他代码(即一些 Worksheet_Change 事件)重置 A1...
  • 无论如何,如果您避免激活和选择内容并直接使用合格范围,您肯定会更好。试试看,有可能解决问题。
  • 如果您在循环开始之前移动BackgroundCalc.Activate,您的问题应该会消失。但我已经发布了一个答案,其中包括代码的重构版本,它应该更健壮。

标签: vba excel


【解决方案1】:

如果在宏启动时CallCalculate 处于活动状态,您复制的第一个单元格将被写入该工作表(覆盖之前可能存在于其单元格 A1 中的任何内容)而不是 @987654322 @ 床单。因此,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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多