2015-01-09 15 views
0

我需要幫助解決我的難題。我寫了一個很好的代碼。現在,用戶不僅希望看到最終結果,還希望看到用VBA編寫的公式(用於審計目的)來驗證結果是否正確。有沒有辦法在同一個單元格中顯示BOTH結果和公式?VBA在單元格中顯示BOTH結果和公式(用於審計目的)

我迄今爲止代碼:

Sub Vlookup_Condition_VAT_table() 
Dim Rng As Range 
Dim i As Long 

Application.ScreenUpdating = False 

Workbooks("GST_recovery_overclaim.xlsm").Worksheets("MonthlyData_Raw").Activate 

'Identify the Destination location to start populating vlookuped values 

Range("AK2").Activate 

With Worksheets("MonthlyData_Raw").Cells 
    Set Rng = .Range("A1:A" & .Cells(.Rows.Count, 1).End(xlUp).Row) 

    For i = 2 To Rng.Rows.Count 

    'populate the destination range with 
    'vlookup values from the list vlookup table 

     Rng.Cells(i, 37) = Application.VLookup(.Cells(i, 28), Sheets("VAT_apportionment_table_201310").Range("D:G"), 4, False) 

    Next 
End With 

Application.ScreenUpdating = True 

End Sub 

非常感謝你, 拉斯

回答

1

如果您沒有查看數千行,您可以嘗試以下操作。

不使用該行打印您的VLOOKUP公式的結果:

Rng.Cells(i, 37) = Application.VLookup(.Cells(i, 28), Sheets("VAT_apportionment_table_201310").Range("D:G"), 4, False) 

您可以改爲把實際的公式中的單元格這一變化

Rng.Cells(i, 37).Formula = "=VLOOKUP(" & _ 
      .Cells(i, 28).Address & "," & _ 
      "'" & Sheets("VAT_apportionment_table_201310").name & "'!D:G," & _ 
      "4," & _ 
      "False)" 

----- ---------更新基於OP COMMENT -----------------------------

添加錯誤捕獲通過ISERROR功能(未測試)

Dim errMsg as String 
errMsg = "Not in exception list" 
Rng.Cells(i, 37).Formula = "=ISERROR(VLOOKUP(" & _ 
      .Cells(i, 28).Address & "," & _ 
      "'" & Sheets("VAT_apportionment_table_201310").name & "'!D:G," & _ 
      "4," & _ 
      "False), " & errMsg & ")" 

由於幾個原因,我爲錯誤消息創建了一個變量。

    調試後
  1. 與式中的文本被髮送到小區這樣可能會非常棘手處理
  2. 容易。並且使用一個變量來繞開這個詭計。
+0

Guitarthrower,是的,它的工作原理。現在我還面臨另一個挑戰:添加ISERROR或IFERROR,並聲明出現錯誤時,請在行中向我提供「Not in exception list」語句。 「」和&&&我已經迷失了。你可以幫幫我嗎?如果你能向我解釋「」和「工作」,我將不勝感激。謝謝!!! – LearnForever

0

也許添加文本的答案和公式的結果。

Rng.Cells(i, 37) = "Answer: " & Application.VLookup(.Cells(i, 28), Sheets("VAT_apportionment_table_201310").Range("D:G"), 4, False) & ", Formula: = Application.VLookup(.Cells(i, 28), Sheets("VAT_apportionment_table_201310").Range("D:G"), 4, False)" 
+0

謝謝,傑森!我會在今天晚些時候測試它。祝你有美好的一天。 – LearnForever

0

如果我不能正確地對待你,你想要顯示在單元格中輸入的公式和結果。這個怎麼樣?

'Assume that you have a Range("A1") equals to = cos(20) 
    Sub GetFormula() 
    Dim MyFormula As String 
    MyFormula = Replace(Range("A1").Formula, "=", "") 
    MsgBox ("Formula is : " & MyFormula _ 
    & " Result is :" & Range("A1")) 
    End Sub 
+0

我假定公式是由用戶輸入的,不涉及VBA。 –

+0

實際上,公式是由VBA添加的,並且計劃是將結果和公式放在同一個單元格中。謝謝你們。我沒有機會測試任何東西...... – LearnForever

相關問題