Excel VBA查找string并在循环中插入一列

我有一个表头,可以从P1到P#(不pipe那个数字是什么)。

我想通过findP2开始创build一个macros,并插入一列,并继续为所有的P(直到它碰到P#)。 然后它将采取创build列,并使单元格的宽度:6.我重新使用公式来find单元格,但我不知道从哪里去。

'在工作表1中findP1

SearchString = "P2" Application.FindFormat.Clear ' loop through all sheets For Each sh In ActiveWorkbook 'Find first instance on sheet Set cl = sh.Cells.Find(What:=SearchString, _ After:=sh.Cells(1, 1), _ LookIn:=xlValues, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False) If Not cl Is Nothing Then selectcell ' if found, remember location With ActiveCell.insertcolumn End If Next 

如何让这个公式select并插入一列,然后重复所有的Ps?

这假定你的第一张表头有你想用作第一行的基线。 这将在现有列的右侧插入新列并调整其大小。

 Public Sub addColumns() Dim intHeaderRow as Integer intHeaderRow = 1 For i = sheets(1).usedrange.columns.count to 1 step -1 addColumn(sheets(1).cells(intHeaderRow, i)) Next End Sub Public Sub addColumn(byval SearchString as string) Dim intColumnFound as integer Application.FindFormat.Clear ' loop through all sheets For Each sh In Worksheets 'Find first instance on sheet Set cl = sh.Cells.Find(What:=SearchString, _ After:=sh.Cells(1, 1), _ LookIn:=xlValues, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False) If Not cl Is Nothing Then intColumnFound = cl.Column sh.Columns(intColumnFound + 1).Insert ' if found, remember location sh.Columns(intColumnFound + 1).ColumnWidth = 6 End If Next End Sub 

当find该值时,您对“记住位置”有一个评论。 我不知道你是否需要这个,所以我把它存储在intColumnFound中,但是它会被覆盖在下一张纸上,而不是在这个代码中使用。