Excelmacros:我想添加一列到一个范围,并调用一个函数来填充它

下面是一个macros,我们用它来构build一个工作表,其中包含一个较大的工作表的子集。 当循环在我们的服务器名称数组中find匹配项时,它将它复制到新的工作表中。 我想在复制过程中添加一个新的列到新的工作表中。 得到这个工作之后,我想通过调用一个函数来填充这个字段。 我们正试图build立一个显示服务器是否为“关键”服务器的列。 简单的y / n从一个看起来关键服务器数组的函数中返回。 我不需要该函数,只需要添加一个列并在循环中填充它。

我将粘贴更大的循环下面,但是这里是单独的代码行,如果发现一个新的工作表复制范围。 在这里,我想添加或复制一个函数填充一列:

Rcount = Rcount + 1 Source.Range("A" & Rng.Row & ":R" & Rng.Row).Copy NewSh.Range("A" & Rcount & ":R" & Rcount) 

这是查询头脑的大循环。 这可能是有用的,或者至lesscertificate这个代码正在被使用:

 With Source.Range("A1:R9000") 'Find where the actual data we need starts Set Rng = .Find(What:="Client", _ After:=.Cells(.Cells.Count), _ LookIn:=xlFormulas, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False) intColorMatch = 0 If Not Rng Is Nothing Then FirstAddress = Rng.Address Do Set Rng = .FindNext(Rng) If (Rng.Interior.Color = 13421772) Then intColorMatch = intColorMatch + 1 End If If (intColorMatch < 2) = False Then StartRow = Rng.Row Exit Do End If Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress End If Source.Range("A" & StartRow & ":R" & StartRow + 1).Copy NewSh.Range("A1:R2") Rcount = 2 FirstAddress = 0 For I = LBound(MyArr) To UBound(MyArr) 'If you use LookIn:=xlValues it will also work with a 'formula cell that evaluates to "@" 'Note : I use xlPart in this example and not xlWhole Set Rng = .Find(What:=MyArr(I), _ After:=.Cells(.Cells.Count), _ LookIn:=xlFormulas, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False) If Not Rng Is Nothing Then FirstAddress = Rng.Address Do If Rng.Row >= StartRow Then Rcount = Rcount + 1 Source.Range("A" & Rng.Row & ":R" & Rng.Row).Copy NewSh.Range("A" & Rcount & ":R" & Rcount) ' Use this if you only want to copy the value ' NewSh.Range("A" & Rcount).Value = Rng.Value End If Set Rng = .FindNext(Rng) Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress End If Next I End With 

如果您想要填充的“新”列在复制数据结束之后,那么您并不是真正添加列 – 您只是填充现有的空列。

如果是这样,你可以说一些像

 NewSh.Cells(Rcount, "Q").Formula = "=whatever_formula_you_want" 

(或使用FormulaR1C1如果更容易)。

或者,如果你只想在那里插入一个值(你正在计算你的VBA代码),这只是

 NewSh.Cells(Rcount, "Q").Value = the_value_I_want