Sub FindAndInsert()
Dim searchRange As Range
Dim foundCell As Range
Dim colNum As Integer
Dim insertCol As Integer
Dim lastRow As Long
Dim insertData As Variant
'设置查找范围为第一行
Set searchRange = Range("1:1")
'查找33
Set foundCell = searchRange.Find(What:=33, LookIn:=xlValues, LookAt:=xlWhole)
If Not foundCell Is Nothing Then
colNum = foundCell.Column
insertCol = colNum '添加一列在找到的列数前面
Columns(insertCol).Insert Shift:=xlToRight '插入列
lastRow = Cells(Rows.Count, insertCol - 1).End(xlUp).Row '获取新列最后一行
insertData = Array("InsertData1", "InsertData2", "InsertData3", "InsertData4", "InsertData5", "InsertData6", "InsertData7", "InsertData8", "InsertData9", "InsertData10", "InsertData11", "InsertData12", "InsertData13") '在新列中插入不同的数据
Range(Cells(2, insertCol), Cells(lastRow, insertCol)).Value = Application.Transpose(insertData)
End If
'查找48
Set foundCell = searchRange.Find(What:=48, LookIn:=xlValues, LookAt:=xlWhole)
If Not foundCell Is Nothing Then
colNum = foundCell.Column
insertCol = colNum '添加一列在找到的列数前面
Columns(insertCol).Insert Shift:=xlToRight '插入列
lastRow = Cells(Rows.Count, insertCol - 1).End(xlUp).Row '获取新列最后一行
insertData = Array("InsertData14", "InsertData15", "InsertData16", "InsertData17", "InsertData18", "InsertData19", "InsertData20", "InsertData21", "InsertData22", "InsertData23", "InsertData24", "InsertData25", "InsertData26") '在新列中插入不同的数据
Range(Cells(2, insertCol), Cells(lastRow, insertCol)).Value = Application.Transpose(insertData)
End If
'查找82
Set foundCell = searchRange.Find(What:=82, LookIn:=xlValues, LookAt:=xlWhole)
If Not foundCell Is Nothing Then
colNum = foundCell.Column
insertCol = colNum '添加一列在找到的列数前面
Columns(insertCol).Insert Shift:=xlToRight '插入列
lastRow = Cells(Rows.Count, insertCol - 1).End(xlUp).Row '获取新列最后一行
insertData = Array("InsertData27", "InsertData28", "InsertData29", "InsertData30", "InsertData31", "InsertData32", "InsertData33", "InsertData34", "InsertData35", "InsertData36", "InsertData37", "InsertData38", "InsertData39") '在新列中插入不同的数据
Range(Cells(2, insertCol), Cells(lastRow, insertCol)).Value = Application.Transpose(insertData)
End If
End Sub
在代码中,首先将要查找的元素定义为33、48和82,然后设置查找范围为第一行。使用Find函数查找每一个元素,并获取它所在的列数。接着,在该列前面插入一列,并在新列中插入13个不同的数据。这里将新列数据设置为不同的数组,可以根据需要进行修改。需要注意的是,在插入数据时,需要使用Application.Transpose函数将一维数组转置成列。最后,循环结束后,新列就会添加到找到的元素所在的列数的前面,而且新列中也会插入13个不同的数据。