Home » excel » Excel VBA. When is it necesary to activate a Sheet?

Excel VBA. When is it necesary to activate a Sheet?

Posted by: admin May 14, 2020 Leave a comment

Questions:

A general answer would be perfect, b
I have this simple code, that only works if Sheet2 is active when running the macro.

Otherwise it gives an error “defined by the application or object”:

Sub PasteArray()
Dim arr(1 To 3) As Variant
Dim n As Integer
Dim ws As Worksheet

arr(1) = 4
arr(2) = 6
arr(3) = 8
n = UBound(arr) - LBound(arr) + 1
Sheets("Sheet2").Range(Cells(1, 1), Cells(n, 1)) = WorksheetFunction.Transpose(arr)
End Sub

It works if I activate the sheet first, but that requires that I save the current active sheet to come back at the end.

Sub PasteArray()
Dim arr(1 To 3) As Variant
Dim n As Integer
Dim ws As Worksheet

arr(1) = 4
arr(2) = 6
arr(3) = 8
n = UBound(arr) - LBound(arr) + 1
Set ws = ActiveSheet
Worksheets("sheet2").Activate
Range(Cells(1, 1), Cells(n, 1)) = WorksheetFunction.Transpose(arr)
ws.Activate

Is it always necesary to do something like this?
I am pretty sure that I have seen some code in which changes to cells in an unactive sheet were made.

Thank you

How to&Answers:

You don’t need to activate a sheet really ever unless you want the user to see something.

You receive an error because of your references, always remember to include Sheet or Worksheet with Ranges:

Sub PasteArray()
    Dim arr(1 To 3) As Variant
    Dim n As Integer
    Dim ws As Worksheet

    arr(1) = 4
    arr(2) = 6
    arr(3) = 8
    n = UBound(arr) - LBound(arr) + 1
    Sheets("Sheet2").Range(Sheets("Sheet2").Cells(1, 1), Sheets("Sheet2").Cells(n, 1)) = WorksheetFunction.Transpose(arr)
End Sub

Added Sheets("Sheets2") before the Cells parts

Honestly would suggest googling how to use With statement in VBA, it would help lots in situations like this