Excel 2010 vba macro ActiveCell.Formula = produces an empty cell when run

microsoft excelmicrosoft-excel-2010vbaworksheet-function

This macro formula (in a loop to place a Vlookup formula for each newly inserted worksheet) results in an empty cell when run:

   ActiveCell.Formula = "=VLookup(""Total Other Operating Expenses"", ActiveWorkbook.Sheets(sheetname).Columns(""H:R""), 7, True)"

the cell is totally blank. I've searched the blogs over several weekends and none have mentioned this result.

I'm using a workaround, "printing" (below) using the very same formula (added some quote marks per some blogs) and it properly creates the formulas in a text file. I then paste the case statements in another macro and when it is called for a particular worksheet it produces the correct formula in the cell just fine. Here is the print statement that creates the case statements in the text file:

    ffile = FreeFile()
    Open MyFile For Output As ffile
    Print #ffile, "Sub SelectTabsFormulas()"
    'create Option1 Vlookups
    Print #ffile, "    Select Case sheetname"
    For FNum = LBound(MyOthExpFiles) To UBound(MyOthExpFiles)
        sheetname = Trim(Mid(MyOthExpFiles(FNum), 6, 4))
        Print #ffile, "    Case " & sheetname & ""
        Print #ffile, "        ActiveCell.Formula = ""=VLookup(""""Total Other Operating Expenses"""", '" & sheetname & "'!H:R, 7, True)"""
        FCnt = FCnt + 1
    Next FNum
    Print #ffile, "    Case Else"
    Print #ffile, "        ActiveCell.Value = """
    Print #ffile, "    End Select"
    Print #ffile, "    "
    Print #ffile, "    Return"
    Print #ffile, "End Sub"
    Close #ffile

Copying the resulting case statements into a macro and it produces the correct formula in the cell:

Sub SelectTabsFormulas()
  Select Case sheetname
    Case 112
      ActiveCell.Formula = "=VLookup(""Total Other Operating Expenses"", '112'!H:R, 7, True)"
    Case 114
      ActiveCell.Formula = "=VLookup(""Total Other Operating Expenses"", '114'!H:R, 7, True)"
    Case 9112
      ActiveCell.Formula = "=VLookup(""Total Other Operating Expenses"", '9112'!H:R, 7, True)"
    Case Else
      ActiveCell.Value = ""
  End Select

  Return
End Sub

Of course my question is why am I getting a blank result? Is there a Windows 7 or Excel Trust Center setting that is preventing the formula insertion?

Best Answer

Change it to this:

ActiveCell.Formula = "=VLookup(""Total Other Operating Expenses"", " & _
                     sheetname & "!H:R, 7, True)"

Your current formula isn't computing ActiveWorkbook.Sheets(sheetname).Columns(""H:R"") because it's inside the string, so it tries to put that in the formula, but the VBA object model isn't accessible from a formula.

Related Question