[英]Using an Excel Macro/VBA to cut and paste data into a newly created row
I want to be able to modify a current report which I am running for my company.我希望能够修改我正在为我的公司运行的当前报告。 The report brings back some basic information on an Event.
该报告带回了有关事件的一些基本信息。 At the end of the data, there is one final column which lists the Event Description.
在数据的末尾,最后一列列出了事件描述。 I want to insert a new row above any row which contains "Totals" and then insert Loss Description: Description.
我想在包含“总计”的任何行上方插入一个新行,然后插入损失描述:描述。
The issue I am running into is that I can't get the "Descriptions" to cut and paste behind Loss Description: in the newly created row.我遇到的问题是我无法在新创建的行中将“描述”剪切并粘贴到 Loss Description: 后面。 I can't post an image of the report but the code I'm using will be below.
我无法发布报告的图像,但我使用的代码将在下面。 When I run the Macro, a new row gets created above the Row which contains "Totals" but the column with the description does not cut and paste.
当我运行宏时,会在包含“总计”的行上方创建一个新行,但带有描述的列不会剪切和粘贴。 The description is in Column Q of the Excel Spreadsheet and the Loss Description: is being created in Column A.
描述在 Excel 电子表格的 Q 列中,损失描述:正在 A 列中创建。
Sub InsertAdj()
Dim LR As Long, i As Integer, n As Integer
LR = Cells(Rows.Count, "A").End(xlUp).Row
For i = LR To 2 Step -1
If Left(Range("A" & i), 6) = "Totals" Then
Rows(i).Insert Shift:=xlDown
n = WorksheetFunction.Match(WorksheetFunction.Lookup("zzzzz", Range("A1:A" & i)), Range("A1:A" & i),
0)
Cells(i, 1) = "Loss Description: " & Cells(n + 1, 16).Value
Cells(n + 1, 16).ClearContents
End If
Next i
End Sub
There's something odd going on on your worksheet where End(xlUp)
doesn't behave as it should - for some reason it stops on empty cells...您的工作表上发生了一些奇怪的事情,其中
End(xlUp)
没有表现出应有的行为 - 由于某种原因,它停在空单元格上......
Tested this alternate approach and it works for me on your sample worksheet:测试了这种替代方法,它适用于您的示例工作表:
Sub InsertAdj()
Dim LR As Long, i As Integer, n As Integer, descCell As Range
Dim sht As Worksheet
Set sht = ActiveSheet
LR = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
For i = LR To 2 Step -1
If Left(sht.Range("A" & i), 6) = "Totals" Then
sht.Rows(i).Insert Shift:=xlDown
'end(xlUp) does not work for some reason, so call a function to find the description
Set descCell = FindDescriptionCell(sht.Cells(i + 1, "Q")) 'call function
sht.Cells(i, 1) = "Loss Description: " & descCell.Value
descCell.ClearContents
End If
Next i
End Sub
Function FindDescriptionCell(c As Range)
Dim f
'search up for a value
Set f = c.EntireColumn.Find(what:="*", after:=c, _
searchorder:=xlByColumns, searchdirection:=xlPrevious)
If Not f Is Nothing Then
'ensure Find didn't loop back below the start cell
If f.Row < c.Row Then Set FindDescriptionCell = f
End If
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.