1

以下のコードでは、エラーが発生します。

Run-time error '1004' Method 'Range' of object'_Worksheet failed.

   Dim destLastCol As Integer 'last column in range
   Dim destLastRow As Integer  'last row in range 
   Dim wsCrewDetail As Worksheet '

   Set wsCrewDetail = Worksheets("CrewDetail_M")
   destLastCol =  integer assigned previously
   destLastRow =  integer assigned previously

   With wsCrewDetail.Range(Cells(4, 1), Cells(destLastRow, destLastCol)) <== error here
    .Sort Key1:=.Cells(4, 2), Order1:=xlAscending, _
     key2:=.Cells(4, 1), Order2:=xlAscending, _
     key3:=.Cells(4, 3), order3:=xlAscending, Header:=xlYes
   End With

参照を設定するさまざまなバリエーションを試して多くの例を検索して見ましたがRange、何も機能していません。

正しい参照構文は何ですか?

destLastRow = 以前に割り当てられた整数を追加するように編集し、destLastCol を表示するように編集

4

1 に答える 1

4

destLastRowこの行に行番号を入力していません
With wsCrewDetail.Range(Cells(4, 1), Cells(destLastRow, destLastCol))

Integerさらに、変数を使用しないでくださいLong。それらはより効率的であり、多数にも対応します。

提案

  • Worksheetなどの短い変数を使用wsすると、コードの入力と読み取りが容易になります
  • Longではなく使用するInteger
  • rng1通常、シートから始まる長いオブジェクトを使用するのではなく、作業範囲 ( ) を設定します。
  • ダミーdestLastRowdestLastCol

サンプルコード

   Dim destLastCol As Long 'last column in range
   Dim destLastRow As Long  'last row in range
   Dim ws As Worksheet
   Dim rng1 As Range

   Set ws = Worksheets("CrewDetail_M")
   destLastCol = 6
   destLastRow = 10

   Set rng1 = ws.Range(ws.Cells(4, 1), ws.Cells(destLastRow, destLastCol))
   With rng1
    .Sort Key1:=.Cells(4, 2), Order1:=xlAscending, _
     key2:=.Cells(4, 1), Order2:=xlAscending, _
     key3:=.Cells(4, 3), order3:=xlAscending, Header:=xlYes
   End With
于 2013-01-13T02:25:13.083 に答える