【问题标题】:UDF (user-defined function) to identify the format pattern for an Excel cell用于识别 Excel 单元格格式模式的 UDF(用户定义函数)
【发布时间】:2021-05-04 13:05:09
【问题描述】:

问题: 我有一张 Excel 表格,在某些单元格中有图案,表明存在某种特征。 我需要为每个具有模式的单元格提供一个数字/文本代码,而不是“无模式/白色”单元格。

example on how it might look before applying the function

由于我没有在 Excel(或一般情况下)中编写 VBA 函数的经验,因此我尝试生成一个 UDF,当单元格具有任何模式时,它只会提供代码。想法是在单元格中编写一个公式,例如:=IntPattern(A1),它将返回单元格 A1 的模式代码。

我尝试实现的代码如下:

Function IntPattern(Pattern As Range) 
Application.Volatile 
IntPattern=Interior.Pattern
End Function

但是,它不起作用。

任何帮助将不胜感激!

【问题讨论】:

    标签: excel vba user-defined-functions


    【解决方案1】:

    关键线应该是

    IntPattern = Pattern.Interior.Pattern
    

    困惑是您自己造成的:您为什么将范围称为“模式”?这是您想要的模式的范围。因此必须在指令中指定。

    从带有 =IntPattern(A2) 之类的单元格调用函数,其中 A2 是从中读取模式的单元格。它可以是包含公式的单元格或任何其他单元格。

    如果引用的单元格没有图案,则返回xlNone = -4142。因此,您的 UDF 的功能可以扩展为,

    Function IntPattern(Pattern As Range)
    
        With Pattern.Interior
            IntPattern = IIf(.Pattern = xlNone, "No pattern", "Pattern " & .Pattern)
        End With
    End Function
    

    如果您需要该功能,可以添加 Application.Volatile

    【讨论】:

      【解决方案2】:

      该功能需要在模块中才能工作。右键单击您的项目,添加一个新模块并粘贴下面的代码。另外,我不会使用 Pattern 这个词作为变量,因为 pattern 是一个属性。试试这个:

      Public Function IntPattern(rng As Range)
          Application.Volatile
          IntPattern = rng.Interior.pattern
      End Function
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多