【问题标题】:Find cell header to copy to查找要复制到的单元格标题
【发布时间】:2017-09-13 07:33:31
【问题描述】:

我有以下问题:我正在尝试自动将数据复制到标题指示的特定列,但它出错:“对象变量或未设置块”。我要做的是将行标题添加到一维数组中,找到与搜索到的 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

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    IF 条件下而不是

    cell_adr = arr(i)
    

    使用

    Set cell_adr = cell
    

    cell 是一个范围,将分配给cell_adr,这又是一个范围。要获取单元格的地址,请使用Debug.Print cell_adr.Address for 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
    

    【讨论】:

      【解决方案2】:

      需要进行一行校正,如下所示,主要是 (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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多