我來晚了黨在這一個,但這裏是我的解決方案。它與已經發布的兩個版本沒有太大區別,但是它的確使用了一個專門設計用於提取函數中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