Matt
Matt

Reputation: 2674

VBA fails when setting range in Excel

Using an example from MSDN I'm trying to set the value of a cell in Excel 2007. Here are the steps I took:

  1. In the Excel options choose Enable all Macro's and Trust access to VBA object model.
  2. Create a new Excel WorkBook.
  3. Add a new VBA Module.
  4. Insert the following function:

    Function MyTest(rg As Range)
        rg.Value = 1
        MyTest = 1234
    End Function
    
  5. Add the formula =MyTest(B1) to the cell at A1.

When the first line of MyTest is executed, the debugger simple fails. Without any error it stops debugging and displays #VALUE! in A1. B1 remains empty.

I've tried setting .Formula instead of .Value. I've tried using ActiveSheet and Worksheets["Sheet1"] to access Worksheets. What can possibly be the cause of this error?

Upvotes: 1

Views: 1906

Answers (1)

David Heffernan
David Heffernan

Reputation: 613612

VBA functions that are called from cell formulae are not allowed to modify cell contents. This restriction is in place so that Excel can keep track of dependencies.

If you need to modify cell contents then you'll have to invoke your VBA through some other mechanism, e.g. a user form.

Upvotes: 7

Related Questions