
나는 이것을 단축할 수 있는 사용자 정의 함수를 만들고 싶었습니다. 따라서 이 작업을 수행할 때마다 if(somefunction(arg)=something,"sometext",somefunction(arg))
복제할 필요가 없습니다 .somefunction(arg)
iferror
if(iserror(somefunction(arg)),"sometext",somefunction(arg)
iftrue(somefunction(arg),"=A1","message")
예를 들어, 나는 다음과 같은 것을 입력할 수 있기를 원합니다 .if(sumfunction(arg)=A1,"message",sumfunction(arg))
나는 시도했다:
Function iftrue(Fx, condition, show)
iftrue = Application.WorksheetFunction.if(Fx & condition, show, Fx)
End Function
하지만 #가치를 줍니다.
내 문제를 진단하기 위해 몇 가지 간단한 기능을 시도하여 어디에서 잘못되었는지 확인했습니다. 그래서 SUM과 If 함수를 복제했습니다.
이 "합계" 기능이 작동합니다.
Function testsum(a, b)
test = Application.WorksheetFunction.Sum(a, b)
End Function
하지만 이 "if" 기능은 작동하지 않습니다.
Function testif(a, b, c)
testif = Application.WorksheetFunction.if(a, b, c)
End Function
그래서 내 문제는 worksheet.function.if
.
대신 VBA ifs를 사용하여 이 문제를 해결할 수 있다는 것을 알고 있지만 실제로는 내가 원하는 것이 아닙니다.
답변1
없다Application.WorksheetFunction.If()
있는 경우에도 if의 테스트 부분에 추가 따옴표를 추가해야 합니다. 예를 들어 fx가 해결되고 "test"
조건이 다음과 같은 경우 "=test"
결과 문자열은 다음과 같습니다."test = test"
넣어
따라서 대신 평가를 사용하세요.
평가를 위해서는 문자열을 특정 형식으로 구문 분석해야 합니다.
결과 문자열에 추가 따옴표를 추가해야 합니다. 예를 들어 fx가 로 확인되고 "test"
조건이 다음과 같은 경우 "=test"
결과 문자열은 "test = test"
.
이것을 Evaluate에 넣으면 함수는 이름이 붙은 함수를 찾습니다 test
. 따라서 ""test"="test""
True로 확인되는 와 같은 문자열이 필요합니다 .
조건이었다면언제나평등과 결코 불평등은 우리가 IF fx = condition then
포함하는 모든 것 대신에 간단히 사용할 수 있습니다 If tst Then
.
이 함수는 불평등을 허용하므로 그보다 더 동적입니다.
Function IFTrue(fx, condition As String, show)
Dim tst As Boolean
Dim z As Integer
Dim t As String
'test whether the condition is assuming "="
If InStr("<>=", Left(condition, 1)) = 0 Then condition = "=" & condition
'Find whether there is one or two qulifiers
If InStr("<>=", Mid(condition, 2, 1)) > 0 Then z = 2 Else z = 1
'Parse string to remove qulifiers from the quotes and make everything a string
t = """" & fx & """" & Left(condition, z) & """" & Mid(condition, z + 1) & """"
'evaluate the formula string to resolve to True or False
tst = Application.Caller.Parent.Evaluate(t)
If tst Then
IFTrue = show
Else
IFTrue = fx
End If
End Function
그런 다음 이렇게 호출합니다.
=IFtrue(SUM(A1,A2),"=A3","Must Be True")
편집하다
IIF()를 사용하고 줄 수를 줄일 수 있습니다
Function IFTrue2(fx, condition As String, show)
Dim z As Integer
'test whether the condition is assuming "="
If InStr("<>=", Left(condition, 1)) = 0 Then condition = "=" & condition
'Find whether there is one or two qulifiers
If InStr("<>=", Mid(condition, 2, 1)) > 0 Then z = 2 Else z = 1
IFTrue2 = IIf(Application.Caller.Parent.Evaluate("""" & fx & """" & Left(condition, z) & """" & Mid(condition, z + 1) & """"), show, fx)
End Function