2017-09-13 52 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