如何在特定位置插入一行

我有一个Excel工作簿,在列'A'中定义了一系列数字。我想在遇到整数值的位置插入一行。

这是我的Excel快照 在这里输入图像描述

我写了一个下面的代码,标识列“A”中的整数值,它将插入一个行。 但问题是即使插入发生在空白处(例如:行号4,8,9和14)。 所以任何人都可以告诉我如何实现插入行只有那些我有Integer的行。

Private Sub CommandButton3_Click() Dim UsedCell, MyRange, intCell Dim Cell_Text As String Dim Cell_Address As String UsedCell = Sheets("Sheet1").Cells(1, 1).SpecialCells(xlLastCell).Row Set MyRange = Range("A2:A" & UsedCell) For Each intCell In MyRange Cell_Text = intCell.Offset(0, 3).Text Cell_Address = intCell.Offset(0, 3).Address FoundRow = intCell.Row If Not InStr(1, intCell.value, ".") > 0 And InStr(1, intCell.value, ".") <> "" Then Range(Cell_Address).Select Selection.EntireRow.Select Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove Else End If Next intCell End Sub 

在数值上使用inStr有点复杂。 另外请注意,Excel会将空单元格解释为值0.尝试以下内容:

 If Int(intCell.Value) = intCell.Value And intCell.Value > 0 Then Debug.Print "insert" End If 

用单词表示:如果单元格值的整数等于单元格值(即没有小数)并且单元格大于零,则执行插入代码。

为了回答OP不得不回答 Teylyn的问题 ,请参阅反向运行Loop基本脚本。

这个例子只是设置单元格A1到A10的Range ,然后以相反的顺序激活它们。

 Option Explicit Sub LoopingInReverse() Dim MyRng As Range Dim MyCellRef As Long Set MyRng = ThisWorkbook.Sheets(1).Range("A1:A10") For MyCellRef = MyRng.Cells.Count To 1 Step -1 Cells(MyCellRef, "A").Activate Next MyCellRef End Sub