简体   繁体   English

用于在Excel中自动添加行的宏

[英]macro for adding rows automatically in excel

I have an excel sheet with thousands of entries as shown in Table A below. 我有一个Excel工作表,其中包含成千上万个条目,如下表A所示。 Now, because of some requirement change, I want to add 3 additional 'TAGS' for each 'Name' as shown in Table B. For example, Name n1 will have tags t1, t2, t3 and t4 and corresponding to each TAG, there will be a separate comment. 现在,由于某些需求的变化,我想为每个“名称”添加3个附加的“标签”,如表B所示。例如,名称n1将具有标签t1,t2,t3和t4,并与每个TAG相对应将是一个单独的评论。 (A) One way to accomplish this would be to add three new rows to each column (it is okay to have 3 blank rows) (B) Another way would be to have 3 more worksheets in the same file corresponding to each tag. (A)一种实现此目的的方法是在每列中添加三个新行(可以有3个空白行)(B)另一种方法是在同一文件中的每个标签对应的位置有3个以上的工作表。 (C) A third way could be to have some filter for the Tag column... (C)第三种方法可能是为Tag列设置一些过滤器...

Could someone please suggest a way to automate (A) above? 有人可以建议一种自动化上述(A)的方法吗? (macro code would be appreciated) and it would be even better if someone can share code to do (C) .. or any elegant solution to the problem. (不胜感激的宏代码),如果有人可以共享代码来执行(C)或解决问题的任何巧妙方法,那就更好了。 Thank you! 谢谢!

TABLE A 表A

Name id Tag     Comment
n1    1  t1    my t1 comment for id 1
n2    2  t1    my t1 comment for id 2
n3    3  t1    my t1 comment for id 3
n4    4  t1    my t1 comment for id 4
n5    5  t1    my t1 comment for id 5

TABLE B 表B

Name  id  Tag         Comment
n1    1   t1        my t1 comment for id 1*
n1    1   t2        my t2 comment for id 1
n1    1   t3        my t3 comment for id 1
n1    1   t4        my t4 comment for id 1
n2    2   t1        my t1 comment for id 2
n3    3   t1        my t1 comment for id 3
n4    4   t1        my t1 comment for id 4
n5    5   t1        my t1 comment for id 5

Tested this code on your table and it should work 在您的表上测试了此代码,它应该可以工作

Sub NewRows()

Dim i As Long
Dim k As Long
Dim lastRow As Long
Dim wb As Workbook
Dim ws As Worksheet

Set wb = ThisWorkbook
Set ws = wb.Sheets("test")
lastRow = Range("B" & Rows.Count).End(xlUp).Row ' I assume that your unique ID's are in column B

For i = lastRow To 2 Step -1 '3 is the first row where you have data
    For k = 4 To 2 Step -1 'Amount of new lines you want to insert
          ws.Rows(i + 1).Insert shift:=xlShiftDown ' insert row
          ws.Range("A" & i + 1).Value = ws.Range("A" & i).Value 'copy value in column A from original entry
          ws.Range("b" & i + 1).Value = ws.Range("b" & i).Value 'copy value in column A from original entry
          ws.Range("C" & i + 1).Value = "T" & k 'update tag info for each new line
          ws.Range("d" & i + 1).Value = "this is " & ws.Range("C" & i + 1).Value & " comment for " & ws.Range("A" & i + 1).Value

    Next k
Next i


End Sub

I am not sure how you populate column D with comments but same principle applies. 我不确定如何用注释填充D列,但适用相同的原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM