Kim Stacks
Kim Stacks

Reputation: 10812

write a vba excel function not knowing parameter is string or dictionary

How do i write a function in excel vba that is something like this in php?

public function name($data) {

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

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

The biggest issue is that i need to define the data type in the function for my parameter

I am expecting either a string or a dictionary that has a key called "0"

Upvotes: 2

Views: 458

Answers (1)

Siddharth Rout
Siddharth Rout

Reputation: 149277

A 0 in dictionary doesn't hold any value. A 1 perhaps can give you the desired result. I don't know php but whatever I could understand from the above code and your requirement, this is what I came up with so I am not sure if this is what you want?

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

EDIT

If you still want to use 0, then while adding to the dictionary, use a 0 for example

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

and then you can use a 0 in the function as below

sName = Inpt.Item(0)

SNAPSHOT (ALL 3 CONDITIONS - USE OF 0 AND 1)

enter image description here

HTH

Sid

Upvotes: 3

Related Questions