excel - 编写一个vba excel函数,不知道参数是字符串还是字典

标签 excel vba function parameters parameter-passing

我如何在 excel vba 中编写一个与 php 中类似的函数

public function name($data) {

  if ($data==="*") {
    return "*";
  }

  if (isset($data[0])) {
    return $data[0];
  }
}

最大的问题是我需要在函数中为我的参数定义数据类型

我期待一个字符串或一个具有名为“0”的键的字典

最佳答案

字典中的0不包含任何值。 1 也许可以给你想要的结果。我不知道 php,但无论我从上面的代码和您的要求中可以理解什么,这就是我想出的,所以我不确定这是否是您想要的?

Sub Sample()
    Dim Dict1 As Dictionary
    Dim sString As String

    Set Dict1 = New Dictionary

    With Dict1
      .CompareMode = BinaryCompare
      .Add 1, "Item 1"
    End With

    sString = "Sid"

    Debug.Print sName(Dict1)
    Debug.Print sName(sString)
End Sub

Public Function sName(Inpt As Variant) As Variant
    If TypeName(Inpt) = "Dictionary" Then
        sName = Inpt.Item(1)
    ElseIf TypeName(Inpt) = "String" Then
        sName = Inpt
    End If
End Function

编辑

如果您仍想使用 0,则在添加到字典时,请使用 0 例如

    With Dict1
      .CompareMode = BinaryCompare
      .Add 0, "Item 1"
    End With

然后您可以在函数中使用0,如下所示

sName = Inpt.Item(0)

快照(所有 3 个条件 - 使用 0 和 1)

enter image description here

HTH

席德

关于excel - 编写一个vba excel函数,不知道参数是字符串还是字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9961962/

相关文章:

c# - excel 或 c# 或 SQL 解决方案来计算期间

excel - 如何将 B 列中的唯一值与 A 列中的奇异值连接起来

用于测试 ping 的 Python 函数

c# - 是否可以不指定工作表名称和列?

excel - 只计算唯一的字符串

regex - 将单元格值转换为 snake_case

vba - Excel VBA 阻止我粘贴值

excel - 在 Excel VBA 中删除一行

c - 如何在 C 语言中对字符串数组进行排序?

python - 在python中获取函数名称作为字符串