23

変数に文字列として格納されているワークシートの名前があります。このワークシートで何らかの操作を実行するにはどうすればよいですか?

私は次のようなことをしますが:

nameOfWorkSheet = "test"
ActiveWorkbook.Worksheets(nameOfWorkSheet).someOperation()

どうすればこれを完了できますか?

4

3 に答える 3

14

あなたが示す方法を使用する、With、および変数を使用するなど、いくつかのオプションがあります。

私の好みは以下のオプション 4 です:Dimタイプの変数でWorksheetワークシートを保存し、変数のメソッドを呼び出すか、関数に渡しますが、どのオプションも機能します。

Sub Test()
  Dim SheetName As String
  Dim SearchText As String
  Dim FoundRange As Range

  SheetName = "test"      
  SearchText = "abc"

  ' 0. If you know the sheet is the ActiveSheet, you can use if directly.
  Set FoundRange = ActiveSheet.UsedRange.Find(What:=SearchText)
  ' Since I usually have a lot of Subs/Functions, I don't use this method often.
  ' If I do, I store it in a variable to make it easy to change in the future or
  ' to pass to functions, e.g.: Set MySheet = ActiveSheet
  ' If your methods need to work with multiple worksheets at the same time, using
  ' ActiveSheet probably isn't a good idea and you should just specify the sheets.

  ' 1. Using Sheets or Worksheets (Least efficient if repeating or calling multiple times)
  Set FoundRange = Sheets(SheetName).UsedRange.Find(What:=SearchText)
  Set FoundRange = Worksheets(SheetName).UsedRange.Find(What:=SearchText)

  ' 2. Using Named Sheet, i.e. Sheet1 (if Worksheet is named "Sheet1"). The
  ' sheet names use the title/name of the worksheet, however the name must
  ' be a valid VBA identifier (no spaces or special characters. Use the Object
  ' Browser to find the sheet names if it isn't obvious. (More efficient than #1)
  Set FoundRange = Sheet1.UsedRange.Find(What:=SearchText)

  ' 3. Using "With" (more efficient than #1)
  With Sheets(SheetName)
    Set FoundRange = .UsedRange.Find(What:=SearchText)
  End With
  ' or possibly...
  With Sheets(SheetName).UsedRange
    Set FoundRange = .Find(What:=SearchText)
  End With

  ' 4. Using Worksheet variable (more efficient than 1)
  Dim MySheet As Worksheet
  Set MySheet = Worksheets(SheetName)
  Set FoundRange = MySheet.UsedRange.Find(What:=SearchText)

  ' Calling a Function/Sub
  Test2 Sheets(SheetName) ' Option 1
  Test2 Sheet1 ' Option 2
  Test2 MySheet ' Option 4

End Sub

Sub Test2(TestSheet As Worksheet)
    Dim RowIndex As Long
    For RowIndex = 1 To TestSheet.UsedRange.Rows.Count
        If TestSheet.Cells(RowIndex, 1).Value = "SomeValue" Then
            ' Do something
        End If
    Next RowIndex
End Sub
于 2012-03-09T05:29:14.270 に答える
3

Ryanの答えを拡張するために、(Dimを使用して)変数を宣言する場合、次の画像のように、VBEの予測テキスト機能を使用して少しごまかすことができます。VBEの予測テキストのスクリーンショット

そのリストに表示されている場合は、そのタイプのオブジェクトを変数に割り当てることができます。つまり、ライアンが指摘したように、ワークシートだけでなく、チャート、範囲、ワークブック、シリーズなどもあります。

その変数を操作するオブジェクトと等しく設定すると、ライアンがこの例で指摘したように、メソッドを呼び出したり、関数に渡したりすることができます。コレクションとオブジェクト(グラフまたはグラフ、範囲または範囲など)に関しては、いくつかの問題が発生する可能性がありますが、試行錯誤を繰り返すことで確実に解決できます。

于 2012-03-09T16:02:36.373 に答える