Cru*_*ler 7 microsoft-excel microsoft-excel-2016
寻找一种方法来实现以下目标。想象我有 2 列
A | B
---------------
NAME | SURNAME
---------------
Ned | Stark
Arya | Stark
Sansa| Bolton
Run Code Online (Sandbox Code Playgroud)
我希望 C 列包含以下内容:“下一个死者将是 NAME 姓氏。干杯!”
所以为了实现这一点,我会制定一个公式
=concatenate(The next to die will be,A2,' ',B2,'. Cheers!')
Run Code Online (Sandbox Code Playgroud)
然后把它拉下来我所有的行
但这是一个微不足道的例子。有时我可能有 20 多列,结果字符串更复杂。必须有更好的方法来做到这一点?我想像 C# 函数“格式”的等效项,例如
=Format('The next to die will be {0} {1}. Cheers!',A2,B2)
Run Code Online (Sandbox Code Playgroud)
有什么建议?
jcb*_*rmu 10
第一个选项:
="The next to die will be "& A2 & ' '& B2 & ". Cheers!"
Run Code Online (Sandbox Code Playgroud)
第二个选项:
(对于铁杆用户)
创建自己的函数:
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
Run Code Online (Sandbox Code Playgroud)
要使其工作,您必须使用ALT+打开 VBA/宏F11,然后在ThisWorkbook下插入一个新模块并粘贴代码。
现在,您可以在任何单元格中放置
=mystring("The next to die will be {0} {1}. Cheers!",A2,B2)
Run Code Online (Sandbox Code Playgroud)
管他呢。请记住,字符串必须先行,然后是单元格引用。
这是有效的:
=mystring("The next to die will be {0}, {3} and {2}. Cheers!",A2,B2,B3)
Run Code Online (Sandbox Code Playgroud)
这不是:
=mystring(A2,"The next to die will be {0}, {3} and {2}. Cheers!",B2,B3)
Run Code Online (Sandbox Code Playgroud)