2016-12-20 14 views
0

特定のセルを別のシートにコピーするコードがあります。新しいレコードには改行が追加されます。 A1を含む新しいシートにコピーされている正しいセルを見ることができるので、処理中にすべてを正しくコピーするように見えます。しかし、これを完了すると、新しいシート(A1)の最初のセルは常に空です。 ここに何が間違っているのかわからない人は、アイデアや提案があれば素晴らしいでしょうか?Excel VBAはシートにコピーされた最初のセルを削除しますか?

事前に感謝

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 
+0

は難しいです。このコードからは来ていません。 'A1'をリセットする他のコード(つまり' Worksheet_Change'イベント)が発生する可能性があります... –

+0

有効にするのを避けて物を選んで、適格な範囲で直接作業すると、どうしても良くなるはずです。試してみてください。問題が解決する可能性があります。 –

+0

ループの開始前に 'BackgroundCalc.Activate'を動かすと、問題はなくなります。しかし、私はコードのリファクタリング版を含む回答を投稿しました。これはより堅牢でなければなりません。 – YowE3K

答えて

2

CallCalculateがアクティブな場合、マクロがを開始すると、あなたの最初のコピーされたセルが(そのセル以前A1であったかもしれない何かを上書きする)そのシートに書き込まれているのではなくBackgroundCalcシートに送信します。したがって、BackgroundCalcのセルA1は、マクロが実行される前と変わらないでしょう(それはおそらく空白でした)。 (同時にバグを修正します)あなたのコードの

Aリファクタリングしたバージョンは、次のようになります推測する

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 
関連する問題