[英]Excel VBA Finding a string and inserting a column on loop
I have a table that has headers that can go from P1 to P# (whatever that number is). 我有一个表,该表的标题可以从P1到P#(无论该数字是多少)。
I want to build a macro that starts out by finding P2 and inserts a column and will continue doing this for all the P's(until it hits P#). 我想建立一个以找到P2开头并插入一列的宏,并将继续对所有P执行此操作(直到命中P#)。 It will then take those created columns and make the cells width: 6. I reused a formula to find the cell, but I don't know where to go from there. 然后将使用这些创建的列并使单元格变宽:6.我重用了一个公式来查找单元格,但是我不知道从那里去哪里。
'Find P1 in sheet 1 '在工作表1中找到P1
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
How do I make this formula select and insert a column, then do it on repeat for all Ps? 如何使该公式选择并插入一列,然后对所有P重复进行此操作?
This assumes your first sheet has the headers you are looking to use as a baseline in the first row. 假设您的第一张纸在第一行中具有要用作基准的标题。 This will insert new columns to the right of the existing column and resize it. 这将在现有列的右侧插入新列并调整其大小。
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
You had a comment to "remember location" when the value was found. 找到该值后,您对“记住位置”发表了评论。 I'm not sure if you needed that, so I stored it in intColumnFound, but it will be overwritten on the next sheet and not used in this code. 我不确定您是否需要它,所以我将其存储在intColumnFound中,但是它将在下一页覆盖,并且在此代码中未使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.