[英]Excel VBA - Call application function (left, right) by name
I would like to be able to call application functions such as left() and right() using a string variable. 我希望能够使用字符串变量调用应用程序函数,如left()和right()。
The reason is that my current code works fine, but has multiple instances of left() and right() that may need to change every time I run it. 原因是我当前的代码工作正常,但有多个left()和right()实例,每次运行时都需要更改。 I'd like to be able to only change it once ("globally") every time.
我希望每次只能改变一次(“全球”)。
After googling, I tried CallByName and Application.Run . 谷歌搜索后,我尝试了CallByName和Application.Run 。 It seems that they only work with a custom class/macro.
它们似乎只适用于自定义类/宏。 Is this true?
这是真的? Is there anything else I should look into?
还有什么我应该研究的吗? I don't need specific code, thank you!
我不需要特定的代码,谢谢!
You can build a custom function where you pass if you want Left
or Right
. 如果您想要
Left
或Right
您可以构建一个自定义函数。
Option Explicit
Sub Test()
Debug.Print LeftRight("L", "StackOverflow", 5)
Debug.Print LeftRight("R", "StackOverflow", 8)
End Sub
Function LeftRight(sWhich As String, sValue As String, iLength As Integer) As String
Select Case sWhich
Case "L": LeftRight = Left(sValue, iLength)
Case "R": LeftRight = Right(sValue, iLength)
End Select
End Function
You just use "L" or "R" as needed. 您只需根据需要使用“L”或“R”。 Change it once and pass as
sWhich
each time. 改变它一次并且每次都传递给
sWhich
。 You can even use a cell reference for this and update the cell before running code. 您甚至可以使用单元格引用并在运行代码之前更新单元格。
Results 结果
Stack
堆
Overflow
溢出
The easiest way around this is to replace all your Left
and Right
calls with a generic function, eg instead of 最简单的方法是用通用函数替换所有的
Left
和Right
调用,例如代替
x = Left("abc", 2)
say 说
x = LeftOrRight("abc", 2)
and then have a function 然后有一个功能
Function LeftOrRight(str As Variant, len As Long) As Variant
'Uncomment this line for Left
LeftOrRight = Left(str, len)
'Uncomment this line for Right
LeftOrRight = Right(str, len)
End Function
Then you can just change the one function as required. 然后您可以根据需要更改一个功能。
You could also use SWITCH
to implement Scott's idea (no error handling if string length is invalid): 您也可以使用
SWITCH
来实现Scott的想法(如果字符串长度无效,则不进行错误处理):
Sub Test()
Debug.Print LeftRight("L", "StackOverflow", 5)
Debug.Print LeftRight("R", "StackOverflow", 8)
End Sub
Function LeftRight(sWhich As String, sValue As String, iLength As Integer) As String
LeftRight = Switch(sWhich = "L", Left$(sValue, iLength), sWhich = "R", Right$(sValue, iLength))
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.