每隔X行将静态文本填充到单元格中



我有一段代码,它每隔X条记录就会填充一个空行。我想做的是有一些代码,然后将一些静态文本插入到那些空行中的单元格中。这是我添加空白行的方法。。。代码不全是我的我从网上找到的。我需要它做的是将静态文本填充到它正在创建的空白行中。然后继续填充并添加每50条记录。谢谢

**********
Sub InsertRowEveryXrows()
   Dim rw As Long
   Dim lr As Long
   Dim cnt As Long
   lr = Range("A" & Rows.Count).End(xlUp).Row
   rw = 2
   cnt = 1
   Do
    If cnt = 50 Then
       Rows(rw).Insert Shift:=xlDown
       cnt = 1
    Else
       cnt = cnt + 1
    End If
    rw = rw + 1
   Loop While rw <> lr
End Sub
*****************

您唯一需要做的就是询问cnt何时将其设置为51并添加静态文本(假设列为1),如下所示:

 Sub InsertRowEveryXrows()
   Dim rw As Long
   Dim lr As Long
   Dim cnt As Long
   lr = Range("A" & Rows.Count).End(xlUp).Row
   rw = 2
   cnt = 1
   Do
     If cnt = 50 Then
         Rows(rw).Insert Shift:=xlDown
         cnt = 1
     Else
        if cnt = 51 then
          cells(rw,1) = "your static text"
        else
         cnt = cnt + 1
        End If
     End If
     rw = rw + 1
   Loop While rw <> lr
 End Sub

告诉我进展如何,希望能有所帮助!

我在代码中添加了注释来显示发生了什么,但这对我有效,应该会更快一些。

Public Sub Sample()
Dim WkSht   As Worksheet
Dim LngLR   As Long 'Last Row
Dim LngCR   As Long 'Current Row
'Connect to the worksheet
Set WkSht = ThisWorkbook.Worksheets("Sheet1")
    'Get the last row so we know when to stop
    LngLR = WkSht.Range("A" & WkSht.Rows.Count).End(xlUp).Row
    LngCR = 51 '51 to account for the first row being a header
    'Keep adding the 50th row until when would end up past the last row
    Do Until LngCR > LngLR
        'Add the new row
        WkSht.Rows(LngCR).Insert Shift:=xlDown
        'Populate it
        WkSht.Range("A" & LngCR) = "Your static text"
        'Increase the last row as it will now be one more
        LngLR = LngLR + 1
        'Got to the next 50th
        LngCR = LngCR + 50
    Loop
Set WkSht = Nothing
End Sub
  • 我把工作表作为一个变量连接起来,因为这是一个很好的做法,你现在所做的工作很好,但读起来可能会很困惑,如果代码变得更模糊,会导致你意想不到的事情发生
  • 我一次增加50,而不是1,从技术上讲,这使它快了50倍,但在今天的计算机上,这一切都很模糊:)
  • 您的代码没有考虑到每次添加一行时最后一行向下移动的情况

最新更新