0

I have created a user defined function (UDF) in Excel VBA, which picks up contents from 2 columns and evaluates to a result. The UDF evaluates correctly when no other workbooks are open, but changes to zero when any other workbooks are opened simultaneously. I think the issue is in the first few steps, where I read the input:

Set Sheet = ThisWorkbook.Worksheets(inputSheet)
For i = 0 To numrows
    array_multi(i, 0) = Cells(inputRow1 + i, inputCol1)
    array_multi(i, 1) = Cells(inputRow2 + i, inputCol2)
Next

Can someone help me resolve the issue here? Let me know if you require more details.

2
  • 1
    Post the whole UDF. Commented Jul 3, 2016 at 7:36
  • Cells() must be referenced in the sheet where they are supposed to be, or the values will be read in the Activesheet. Commented Jul 4, 2016 at 7:51

2 Answers 2

2

In your code you use the Sheet which you never use when assigning values to your array.

Set Sheet = ThisWorkbook.Worksheets(inputSheet)
array_multi(i, 0) = Cells(inputRow1 + i, inputCol1)
array_multi(i, 1) = Cells(inputRow2 + i, inputCol2)

Try using the Sht.Cells to make sure your array reads the values from the right worksheet and workbook.

Set Sht = ThisWorkbook.Worksheets(inputSheet)
For i = 0 To numrows
    array_multi(i, 0) = Sht.Cells(inputRow1 + i, inputCol1)
    array_multi(i, 1) = Sht.Cells(inputRow2 + i, inputCol2)
Next
Sign up to request clarification or add additional context in comments.

7 Comments

I thought ThisWorkbook was specifically about not taking different values but always be the workbook the code is in.
@arcadeprecinct you are right, just need to fix the reference to the Sht object
ah I missed the missing sheet reference in the next lines. So the problem is that ActiveSheet which is used by Cells is changing.
@arcadeprecinct feel free to +1 :)
Your solution is probably the right fix but tbh I'm not convinced by the explanation
|
0

The Cells object refers to the ActiveWorkbook.ActiveSheet unless qualified. You could use

With ThisWorkbook.Worksheets(inputSheet)
    For i = 0 To numrows
        array_multi(i, 0) = .Cells(inputRow1 + i, inputCol1)
        array_multi(i, 1) = .Cells(inputRow2 + i, inputCol2)
    Next i
End With  

As Shai's answer is 100% right please accept and upvote his answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.