我想创建一个宏来在报告中添加额外的信息。
有时候"消息"列不在同一位置(可以在B,D或E列中)。所以我在考虑一些步骤:
1.找到"消息"列。
2.在左侧插入栏目
3.根据不同情况添加额外信息。 (这是问题)
Sub Extra()
With Worksheets(1).Range("a1:x1")
Set c = .FIND("Message", LookIn:=xlValues)
If Not c Is Nothing Then
c.EntireColumn.Select
Selection.Insert
End If
End With
'3rd step
Dim d As Range
For Each d In Selection
Select Case d.Value
Case Is = "D1"
'add text CCC
Case Is = "D2"
'add text BBB
Case Is = "D345"
'add text CCC
End Select
Next d
End sub
如何制作此宏?
答案 0 :(得分:1)
我设法对此进行了测试,并且按预期运行:
Sub foo()
Set res = Sheet1.Cells(1, 1).EntireRow.Find(What:="Message", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False) 'Find column with header of "Message"
ColumnNumber = res.Column 'Get ColumnNumber
Columns(ColumnNumber).EntireColumn.Insert 'Insert a new column
LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row ' Find the last Row on column A
Sheet1.Cells(1, ColumnNumber).Value = "Extra Info" 'add header for new column
For i = 2 To LastRow 'loop through the sheet to add the extra info
If Sheet1.Cells(i, ColumnNumber + 1).Value = "D1" Then Sheet1.Cells(i, ColumnNumber).Value = "AAA"
If Sheet1.Cells(i, ColumnNumber + 1).Value = "D2" Then Sheet1.Cells(i, ColumnNumber).Value = "BBB"
If Sheet1.Cells(i, ColumnNumber + 1).Value = "D345" Then Sheet1.Cells(i, ColumnNumber).Value = "CCC"
Next i
End Sub