2017-09-13 56 views
0

我有以下问题:我试图自动将数据复制到头指定的某个列,但它出错:“对象变量或未设置块”。我想要做的是将行标题添加到一维数组,找到与搜索到的mth_exp_PM相匹配的范围,并将其存储在另一个变量中,最好是设置范围(单元格?)以便进一步复制。查找单元头复制到

我在做什么错?如果此解决方案不正常,那么根据行标题复制到列的最佳/更简单的解决方案是什么?

谢谢!

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

IF条件代替

cell_adr = arr(i) 

使用

Set cell_adr = cell 

cell是一个范围,并且将被分配到cell_adr这又是一个范围。要获取单元格的地址,请使用Debug.Print cell_adr.Address,地址为Debug.Print cell_adr

如果您不在代码的其他任何地方使用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

一个线校正需要,如下,majorly(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