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

标签 vba excel lookup-tables vlookup

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

=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列时,将运行宏以输入正确的数据。

最佳答案

如果必须使用 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

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

问题就变成了您想要多久强制/覆盖这些单元格?您可以将此宏与“事件”联系起来,例如每当工作簿文件打开时,或者每当工作表上的值发生更改时,或者每当有人手动更改您不希望他们更改的单元格时,等等。

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

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

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

关于vba - 如何将单元格查找转换为VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14947998/

相关文章:

vba - 无法使 vlookup 工作

excel - 将数字转换为文本时防止舍入

Python:如何使用 xlwt 编写复数到 Excel?

excel - 在不同的标准中排名前 5 名

tensorflow - tf.contrib.lookup.HashTable 问题

c# - 我应该使用查找列表而不是大量乘法吗?

arrays - 分割函数: Text from a cell into an array but ignore the blank lines

excel - 如何使VBA函数 "VBA only"并将其作为UDF禁用

excel - 在值列表中搜索所有值并将所有找到的值返回到相邻单元格中

java - 我应该如何实现一个包含需要以不同语言显示的项目列表的下拉框?