UDF(用户定义的函数)用于识别 Excel 单元格的格式模式

UDF (user-defined function) to identify the format pattern for an Excel cell

问题: 我有一个 Excel sheet 在某些细胞中有模式,表明存在某种特征。 除了“无 pattern/white”单元格之外,我需要为每个具有模式的单元格提供 numeric/text 代码。

example on how it might look before applying the function

由于我没有在 Excel 中编写 VBA 函数的经验(或一般来说),我尝试生成一个 UDF,当单元格有任何模式时,它只提供一个代码。想法是在单元格中写入一个公式,例如:=IntPattern(A1),这将 return 单元格 A1 的模式代码。

我尝试实现的代码如下:

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

然而,它不起作用。

任何帮助将不胜感激!

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

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

临界线应该是

IntPattern = Pattern.Interior.Pattern

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

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

如果引用的单元格没有模式,return 将是 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