3

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

=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,以便使用此公式对整个列进行加密?

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

我避免锁定单元格,因此查看 VBA 来执行此操作。

编辑:

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

现在如何制作数据,例如09-02-18022013-03383-A,当输入到A列时,它将运行宏来输入正确的数据。

4

1 回答 1

2

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

首先,将它放在工作表的模块中。这将导致每次对 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

因此,以编程方式插入普通公式相当容易。

那么问题就变成了你想多久强制/覆盖这些单元格?您可以将此宏绑定到“事件”,例如,无论何时打开工作簿文件,或每当工作表上的值发生更改,或每当有人手动更改您不希望它们更改的单元格时,等等。

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

或者,您可以纯粹在 vba 中“重写公式”。替换cl.Formula = strFormulacl.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

但这需要更多地了解触发此宏的频率/事件,因为单元格将没有任何公式(公式/计算仅在用户或事件触发器请求时在内存中执行)。

于 2013-02-19T01:16:46.923 回答