如何将单元格查找转换为VBA

目前,我在我的单元格中有一个公式:

=IFERROR(VLOOKUP(A:A,'Daily Report'!A:Z,2,FALSE),"") =IFERROR(VLOOKUP(A:A,'Daily Report'!A:Y,7,FALSE)&", "&VLOOKUP(A:A,'Daily Report'!A:Y,8,FALSE)&", #"&VLOOKUP(A:A,'Daily Report'!A:Y,9,FALSE)&"-"&VLOOKUP(A:A,'Daily Report'!A:Y,10,FALSE)&", Singapore "&VLOOKUP(A:A,'Daily Report'!A:Y,11,FALSE),"") 

如何将其转换为VBA,以便整个列将使用此公式进行encryption?

我的公式总是被使用我的Excel表格的人取代。

我正在避免locking单元格,因此查看VBA执行此操作。

编辑:

MACRO

 Sub vlookup() Dim LR As Long LR = Cells(Rows.Count, "A").End(xlUp).Row Range("D2").Select ActiveCell.FormulaR1C1 = _ "=IFERROR(VLOOKUP(C[-3],'Daily Report'!C[-3]:C[22],2,FALSE),"""")" Selection.AutoFill Destination:=Range("D2:D" & LR), Type:=xlFillDefault End Sub 

现在如何input数据,例如input到A列,就会运行macrosinput合法的数据。

如果您必须使用VBA,最简单的方法是在受影响的单元格中重写公式:

首先,将其放置在Worksheet的模块中。 这会导致macros在每次更改列A时触发。

 Private Sub Worksheet_Change(ByVal Target as Range) If Not Intersect(Target,Me.Range("A:A")) Is Nothing Then Application.EnableEvents = False 'to disable infinite loop InsertFormula Application.EnableEvents = True End If End Sub 

然后,把它放在一个普通的代码模块中:

 Sub InsertFormula() Dim rng as Range 'this will set the range in which you want this formula to appear Dim cl as Range 'cell iterator within rng variable Dim strFormula1 as String `string to hold the formula text set rng = Range("B2:B39") 'Change this range to the desired range strFormula = "=IfError(Vlookup(A:A,'Daily Report'!A:Z,2,False),"")" For Each cl in rng cl.Formula = strFormula Next End Sub 

所以,以编程方式插入一个正常的公式是相当容易的。

那么问题就变成了你想要强制/覆盖这些单元的频率? 您可以将此macros与“事件”关联起来,例如,无论何时打开工作簿文件,或工作表中的值发生更改,或者只要有人手动更改您不希望它们更改的单元格等等。

你的第二个公式可以做同样的事情,只需添加另一个Rangevariables(例如Dim rng2 as Range )和另一个stringvariables来保存公式文本(例如strFormula2 )。

另外,你也可以用vba来“重写公式”。 将cl.Formula = strFormulareplace为cl.Value = MyLookupFormula ,并将此函数添加到包含上述子例程的代码模块中:

 Function MyLookupFormula() as Variant 'Performs equivlanet to worksheet function If Not IsError(Application.WorksheetFunction.Vlookup(Range("A:A"),Sheets("Daily Report").Range("A:Z"),2,False)) Then myLookupFormula = (Application.WorksheetFunction.Vlookup(Range("A:A"),Sheets("Daily Report").Range("A:Z"),2,False)) Else: myLookupFormula = vbNullString End Function 

但是这需要知道更多的事件触发macros的频率/事件,因为单元格不会有任何公式(公式/计算仅在用户请求或事件触发时才在内存中执行)。