Excel 函数将变量插入字符串

Excel 函数将变量插入字符串

寻找实现以下目标的方法。假设我有 2 列

A    |   B
---------------
NAME |   SURNAME
---------------
Ned  | Stark
Arya | Stark
Sansa| Bolton

我希望 C 列包含以下内容:“下一个死去的人将是 NAME Surname。干杯!”

为了实现这一点,我会制作如下公式

=concatenate(The next to die will be,A2,' ',B2,'. Cheers!')

然后将其拉下所有行

但这只是一个简单的例子。有时我可能有超过 20 列,而生成的字符串则要复杂得多。一定有更好的方法来做到这一点?我正在考虑一个等同于 c# 函数“Format”的函数,例如

=Format('The next to die will be {0} {1}. Cheers!',A2,B2)

有什么建议么?

答案1

第一种选择:

="The next to die will be "& A2 & ' '& B2 & ". Cheers!"

第二种选择:

(针对铁杆用户)

创建您自己的函数:

Function myString(ParamArray Vals() As Variant)
    Separator1 = "{"
    Separator2 = "}"
    finalString = ""
    initialString = Vals(0)
    found = True
    firstpos = 1
    While found = True
        pos = InStr(firstpos, initialString, Separator1)
        If pos = 0 Then
            found = False
            endpartval = Mid(initialString, firstpos)
            finalString = finalString + endpartval
        Else
            stringParts = Mid(initialString, firstpos, pos - firstpos)
            pos1 = InStr(pos, initialString, Separator2)
            firstpos = pos1 + 1
            varNumber = Mid(initialString, pos + 1, pos1 - pos - 1)
            finalString = finalString + stringParts + Vals(varNumber + 1)
        End If
    Wend
    myString = finalString
End Function

为了使其工作,你必须用ALT+打开 VBA/Macros F11,然后在本工作簿插入一个新模块并粘贴代码。

现在,你可以把

=mystring("The next to die will be {0} {1}. Cheers!",A2,B2)

或其他。请记住,字符串必须先去,然后单元格引用。

这是有效的:

=mystring("The next to die will be {0}, {3} and {2}. Cheers!",A2,B2,B3)

这不是:

=mystring(A2,"The next to die will be {0}, {3} and {2}. Cheers!",B2,B3)

答案2

Excel 中没有这样的函数,您可以使用SUBSTITUTE,但它仍然会很长:

=SUBSTITUTE(SUBSTITUTE("The next to die will be {1} {2}","{1}",A2),"{2}",B2)

答案3

对上述函数进行了轻微改进。将 + 替换为 &,以便处理非字符串单元格

Function myString(ParamArray Vals() As Variant)
    Separator1 = "{"
    Separator2 = "}"
    finalString = ""
    initialString = Vals(0)
    found = True
    firstpos = 1
    While found = True
        pos = InStr(firstpos, initialString, Separator1)
        If pos = 0 Then
            found = False
            endpartval = Mid(initialString, firstpos)
            finalString = finalString + endpartval
        Else
            stringParts = Mid(initialString, firstpos, pos - firstpos)
            pos1 = InStr(pos, initialString, Separator2)
            firstpos = pos1 + 1
            varNumber = Mid(initialString, pos + 1, pos1 - pos - 1)
            finalString = finalString & stringParts & Vals(varNumber + 1)
        End If
    Wend
    myString = finalString
End Function

相关内容