2017-09-13 8 views
0

次の問題があります。ヘッダーで示されている特定の列へのデータのコピーを自動化しようとしていますが、「オブジェクト変数またはブロックが設定されていません。私がしようとしているのは、1次元配列に行ヘッダーを追加し、検索されたmth_exp_PMに一致する範囲を見つけて、別の変数、好ましくは設定範囲(セル?)に格納してコピーすることです。コピーするセルヘッダーを見つける

私は間違っていますか?この解決策がOKでない場合は、行ヘッダーに基づいて列にコピーする最も簡単なソリューションは何ですか?

ありがとうございました! IF状態で

dim i as long 
dim cell, cell_adr as range 
dim arr() as string 
dim mth_exp_PM as string 'this value is taken from a different workbook and it matches one row header value 

i = 0 
For Each cell In Range(Range("D1"), Range("D1").End(xlToRight).Offset(0, -1)).Cells 
    ReDim Preserve arr(i) 
    arr(i) = cell 
    If arr(i) = mth_exp_PM Then 
     cell_adr = arr(i) 
     Debug.Print cell_adr 
    End If 
    i = i + 1 
Next cell 

Image

答えて

1

代わりに

cell_adr = arr(i) 

使用

Set cell_adr = cell 

cellの範囲であり、再び範囲であるcell_adrに割り当てられます。セルのアドレスを取得するには、Debug.Print cell_adrの場合はDebug.Print cell_adr.Addressを使用します。

arrをコード内の他の場所で使用していない場合は、コードを削除できます。以下のコードでは、配列を使用する必要がない場合には必須ではない行についてコメントしました。以下のように、必要に応じて

Sub Demo() 
    'Dim i As Long 
    Dim cell As Range, cell_adr As Range 'declare cell as Range 
    'Dim arr() As String 
    Dim mth_exp_PM As String 'this value is taken from a different workbook and it matches one row header value 

    'i = 0 
    For Each cell In Range(Range("D1"), Range("D1").End(xlToRight).Offset(0, -1)).Cells 
     'ReDim Preserve arr(i) 
     'arr(i) = cell 
     'If arr(i) = mth_exp_PM Then 
     If cell = mth_exp_PM Then 
      Set cell_adr = cell 
      Debug.Print cell_adr.Address 
     End If 
     'i = i + 1 
    Next cell 
End Sub 
0

1行補正、すぎなかった(arr(i) = cell.value

怒鳴るはあなたのコード改訂修正を発表しました。

dim i as long 
dim cell, cell_adr as range 
dim arr() as string 
dim mth_exp_PM as string 'this value is taken from a different workbook and it matches one row header value 

i = 0 
For Each cell In Range(Range("D1"), Range("D1").End(xlToRight).Offset(0, -1)).Cells 
    ReDim Preserve arr(i) 
    arr(i) = cell.value 'Do correct here! 
    If arr(i) = mth_exp_PM Then 
     Set cell_adr = cell 'Correct here! 
     Debug.Print cell_adr.Address 'and Correct here 
    End If 
    i = i + 1 
Next cell 
関連する問題