[Excel VBA] How to Move to and Select Cell Ranges on Non-Active Sheets | Using Application.GoTo

目次

Introduction

In Excel VBA, it is common to encounter situations where you need to move to or select a cell range located on a different sheet.

However, since Range(...).Select can only be used on the currently active sheet, attempting to select a range across different sheets will result in an error.

In this article, I will explain how to reliably move to a cell on a non-active sheet by utilizing the Application.GoTo method.


Incorrect Example: Direct .Select Fails

Worksheets("InputSheet").Range("C3:F12").Select  '← Fails if the sheet is not active

If you use .Select while “InputSheet” is not the active sheet, a runtime error will occur.


Correct Method: Using Application.GoTo to Move

Application.GoTo Worksheets("InputSheet").Range("C3:F12")

Explanation:

  • Application.GoTo is a method that allows you to move focus to any cell or range regardless of the currently active sheet.
  • The code above jumps to the range C3:F12 on “InputSheet” and selects it.
  • The target sheet automatically becomes active, and the specified cell range is selected.

Application: Continuing Processing After Selection

With Worksheets("InputSheet")
    ' Move to the range
    Application.GoTo .Range("C3:F12")
    
    ' Perform subsequent operations (e.g., changing background color)
    .Range("C3:F12").Interior.Color = RGB(255, 255, 200)
End With

By using a With block, you can clearly define subsequent operations, such as applying colors or manipulating values for the specified range.


Important Points and Notes

PointDescription
Avoid .Select.Select results in an error if the target sheet is not active.
GoTo moves focusApplication.GoTo enables cell movement across different sheets.
Optional ArgumentsBy setting the second argument to Scroll:=True, you can also control the scroll position.

Example Use Cases

  • Jumping to an input field on a specific sheet.
  • Displaying error cells on a different sheet to provide supplementary explanations.
  • Clearly indicating the starting point of a process between multiple sheets.

Summary

ActionCode ExampleNotes
Select cells across sheetsApplication.GoTo Worksheets("SheetName").Range("Range")Safely move to any cell.
Incorrect usage (.Select)Worksheets(...).Range(...).SelectOnly usable on the active sheet.
Continuing processingUse .Range(...).Value or .Interior.ColorPossible to format or set values after moving.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次