我来晚了党在这一个,但这里是我的解决方案。它与已经发布的两个版本没有太大区别,但是它的确使用了一个专门设计用于提取函数中LOOKUP的评估值的函数,并返回函数中已更改的公式。这样,如果您循环遍历一系列单元格,则可以根据特定条件选择调用函数,例如,如果单元格具有公式,或者隐藏或者类似的话。
这里的功能:
Function ExtractVLOOKUPValue(rng As Range) As Variant
' This will extract the returned value of the first instance
' of a VLOOKUP formula in a cell.
' Constant declarations.
Const sVLOOKUP As String = "VLOOKUP"
Const lVLOOKUP_LEN As String = 7
Const sOPEN_PAREN As String = "("
Const sCLOSE_PAREN As String = ")"
' Variable declarations.
Dim lVlookupPos As Long
Dim lCnt As Long
Dim lParenCnt As Long
Dim sVlookupFormula As String
Dim sResult As String
' Check first if the cell is a formula, and then
' if a VLOOKUP formula exists in the cell.
If rng.HasFormula Then
lVlookupPos = InStr(rng.Formula, sVLOOKUP)
If lVlookupPos <> 0 Then
' Isolate the VLOOKUP formula itself.
For lCnt = lVlookupPos To Len(rng.Formula)
' Count the open parentheses we encounter so that we can use
' the apporpriate number of closing parentheses.
If Mid(rng.Formula, lCnt, 1) = sOPEN_PAREN Then lParenCnt = lParenCnt + 1
' If we get to closing parenthese, start taking counts away from the
' parencnt variable so we can keep track of the correct number of
' parenthesis in hte formula.
If Mid(rng.Formula, lCnt, 1) = sCLOSE_PAREN Then
lParenCnt = lParenCnt - 1
' If we get done to zero in the parencnt, then extract the formula.
If lParenCnt = 0 Then
sVlookupFormula = Mid(rng.Formula, lVlookupPos, lCnt + 1 - lVlookupPos)
Exit For
End If
End If
Next lCnt
End If
End If
' Now that we have the formula, we can evalutate the result.
On Error Resume Next
sResult = Evaluate(sVlookupFormula)
' If we errored out, return the #N/A in the function.
If Err.Number <> 0 Then
sResult = "#N/A"
End If
' Replace the VLOOKUP in the formula with the result, then return it to the function.
sResult = Replace(rng.Formula, sVlookupFormula, sResult)
' Return the result, having replaced the VLOOKUP function.
ExtractVLOOKUPValue = sResult
End Function
而且这里是你会如何称呼它:
Sub ReplaceFormulaWithValue()
Dim rng As Range
Dim rCell As Range
Set rng = Selection
For Each rCell In rng
rCell.Formula = ExtractVLOOKUPValue(rCell)
Next rCell
End Sub
商店VLOOKUP到一个变量? – findwindow
抱歉,请清楚您的问题和期望 – Siva
您可以使用InStr查找启动VLOOKUP的字符#,然后再次查找Intr以查找VLOOKUP的右括号中的字符#。您可以使用MID和REPLACE来计算查找的整个字符串。这假设VLOOKUP中没有嵌套公式。 – Tom