2017-11-29 8 views
0

Sheet2の列Mのセルが「Special」に変更された場合、そのセルの行番号がSheet12の列Bにコピーされるというスクリプトを作成しています。行番号が列内で最大の行番号の場合は、最後に追加されます。そうでない場合は、行がテンプレート行からコピーされ、行番号とともに挿入され、列Bのすべての数字が連続するようにします。ループ内の空のセルを検索

中間シーケンス番号を挿入/コピーするコードは機能しますが、最後に最大番号を追加するようには機能していません。私は間違いがない。それだけで動作していない。ここでのコードは、(シート2中)は次のとおり

If Target.column = 13 Then 

    Dim cell As Integer 
    Dim l As Long 

    cell = ActiveCell.Row 

    If ActiveCell.Value = "Special" Then 
     With Sheet12 
      For l = .Cells(rows.count, "B").End(xlUp).Row To 3 Step -1 
       If .Cells(l, 2).Value = vbNullString And .Cells(l - 1, 2).Value < cell Then 
        Sheet12.Cells(l, 2).Value = cell 
       ElseIf .Cells(l, 2).Value > cell And .Cells(l - 1, 2).Value < cell Then 
        Sheet12.Cells(l, 2).EntireRow.Insert shift:=xlDown 
        Sheet12.Range("A3").EntireRow.Copy Sheet12.Cells(l, 2).EntireRow 
        Sheet12.Cells(l, 2).Value = cell 
       End If 
      Next 
     End With 
    End If 
End If 

変更する必要があるコードの一部がIf .Cells(l, 2).Value = vbNullString And .Cells(l - 1, 2).Value < cell Thenあります。私は、空のセル(すなわちisempty()、 ""など)をチェックし、セルをシート名で別々に参照するさまざまな方法を試しました。何か案は?あなたの助けを前もってありがとう!

+1

セルをセル単位でループするのはなぜですか? 'GoTo> Special Cells'はVBAで使うことができます:http://www.ozgrid.com/VBA/special-cells.htm –

+0

セルでループする必要があると思います。既存の番号(コピー/挿入スクリプトを実行する)と最大数(最後に追加する)の間の数字です。 – Kim

+1

一度にすべてを行う必要はなく、B列に新しい値を挿入する場所を見つけようとしています。もっと簡単な方法は、列Bの末尾に追加して、それを並べ替えることです。 – Ibo

答えて

0

問題は、ループがB列の最初の空白でないセルから開始していたため、その値がvbnullstringであることができなかったことです。

If Target.column = 13 Then 

    Dim cell As Long 
    Dim l As Long 

    cell = ActiveCell.Row 

    If ActiveCell.Value = "Special" Then 
     If Sheet12.[B4].Value = vbNullString Then 
      Sheet12.[B4].Value = cell 
     Else 
      With Sheet12 
       For l = .Cells(rows.count, "B").End(xlUp).Row + 1 To 4 Step -1 
        If .Cells(l, 2).Value = vbNullString And .Cells(l - 1, 2).Value < cell Then 
         Sheet12.Cells(l, 2).Value = cell 
         Exit For 
        ElseIf .Cells(l - 1, 2).Value > cell And .Cells(l - 2, 2).Value < cell Then 
         Sheet12.Cells(l - 1, 2).EntireRow.Insert shift:=xlDown 
         Sheet12.Range("A3").EntireRow.Copy Sheet12.Cells(l - 1, 2).EntireRow 
         Sheet12.Cells(l - 1, 2).Value = cell 
         Exit For 
        End If 
       Next 
      End With 
     End If 
    ElseIf ActiveCell.Value = vbNullString Or ActiveCell.Value = "Normal" Then 
      With Sheet12 
       For l = .Cells(rows.count, "B").End(xlUp).Row To 4 Step -1 
        If .Cells(l, 2).Value = cell Then 
         .Cells(l, 2).EntireRow.Delete 
        End If 
       Next 
      End With 
    End If 
End If 

注:以下のコードを働いているコメントで述べたように、これは、実行する最も効率的な方法ではありません。しかし、誰かが同様の問題を抱えている場合は、その修正方法を説明したかったのです。

関連する問題