【问题标题】:Why is formula being used on blank cells in a range?为什么要在范围内的空白单元格上使用公式?
【发布时间】:2022-01-02 22:05:52
【问题描述】:

我仅循环通过 ResultsTable 的 A 列。 ResultsTable 的 A 列包含 FirstNames 列表。如果 ResultsTable 的 A 列中的行具有值,则将 XLOOKUP 公式应用于 ResultsTable 的 B 列,该公式将 ResultsTable 中的 FirstName 与 LookupTable 中的 FirstName 匹配。如果ResultsTable 中的FirstName 与LookupTable 中的FirstName 匹配,则从LookupTable 中获取与FirstName 关联的LastName,并将该LastName 放入ResultsTable 的B 列中。仅当在 ResultsTable 的 A 列中找到 FirstName 时才应执行此操作(即,如果“A2”具有 FirstName 值,则应用公式将 LastName 从 LookupTable 放入 ResultsTable 的单元格“B2”)。因此,下面的代码有效,但是当 ResultsTable 的 A 列中的行中没有 FirstName 时,公式将应用于 ResultsTable 的 B 列中的行(即下面的代码将公式应用于“B50”,即使“A50”为空白)。在 ResultsTable 中包含 FirstName 的列 A 中的行数将是一个动态范围。仅当 ResultsTable 的 A 列具有 FirstName 值时,如何将下面的代码获取到 ResultsTable 的 B 列中的 XLOOKUP 公式?下面是代码的样子:

Sub Test()
    'Declare variables
    Dim wbk As Workbook, wsLookupTable As Worksheet, wsResultsTable As Worksheet 
    Dim rng As Range, FirstNames As Variant, i As Long
    'Set variables
    Set wbk = ThisWorkbook
    Set wsLookupTable = wbk.Worksheets("LookupTable")
    Set wsResultsTable = wbk.Worksheets("ResultsTable")
    'Activate the ResultsTable
    wsResultsTable.Activate
    With wsResultsTable
        'Set the Range to the UsedRange of Column A of the ResultsTable
        Set rng = wsResultsTable.UsedRange.Columns("A")
        'Set the FirstNames array to the Range of Column A of the ResultsTable
        FirstNames = rng
        'Use a For loop to search the Range in the ResultsTable
        For i = LBound(FirstNames, 1) To UBound(FirstNames, 1)
            'If FirstName in Column A has a value (i.e. not empty)
            If FirstNames(i, 1) <> "" Then
                'Use a XLOOKUP formula to match FirstName of ResultsTable
                'To the FirstName of the LookupTable
                'Put value of the LastName that matches the FirstName in the LookupTable
                'Into Column B of the ResultsTable
                rng(i, 2).FormulaR1C1 = _
                "=XLOOKUP([@FirstName],LookupTable[FirstName],LookupTable[LastName])"
            End If
        Next i
    End With
End Sub

非常感谢。

【问题讨论】:

  • 不知道 A 列的值如何,我建议使用 trim(FirstNames(i,1)) 以确保忽略空格。此外,在循环之前 debug.print 或停止代码以查看 UBound(FirstNames, 1) 的值。
  • 该表格是实际的 Excel 表格,因此可能会自动填充公式吗?
  • 是的,它们是实际的 Excel 表格,是的,它会自动填充公式。当A列中没有值时,如何阻止它自动填充公式?并且修剪 A 列中的值并没有什么不同。
  • QHarr 让我想到了解决方案,最终它非常容易。我所要做的就是通过添加以下行来禁用 Excel 自动填充公式:Application.AutoCorrect.AutoFillFormulasInLists = False

标签: excel vba loops xlookup


【解决方案1】:

在公式中添加 IF 语句以检查 FirstName 是否为空。如果为空,则写入一个空字符串。如果不为空,请执行 XLOOKUP。

我的语法可能有误,请相应调整。

rng(i, 2).FormulaR1C1 = "=IF([@FirstName] = """", """", XLOOKUP([@FirstName],LookupTable[FirstName],LookupTable[LastName]))"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多