首页 > 解决方案 > 为什么它没有将任何值转移到另一张纸上?

问题描述

我想将值从工作表“COMP”复制到同一工作簿中的另一个工作表“BOM”,但下面的代码没有这样做。

“COMP”表有一个范围“COMP range”,它是一个表格,其中第一列是设备列表,其余列包含与这些设备对应的部件。

我正在编写代码以查找特定设备并将其相应部分复制到另一张表(在同一工作簿中)并转置它们。

Sub COMP_PARTS()

COMP1 = "EQUIPMENT 1"

        With Worksheets("COMP").Range("COMP_range")
            NOROWS = .Rows.Count
        For I = 1 To NOROWS
            If (.Cells(I, 1) = COMP1) Then
                 For II = 2 To 29

                   ThisWorkbook.Sheets("COMP").Cells(I, II).Copy
                  ThisWorkbook.Sheets("BOM").Cells(II, 4).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

                  Next II
            End If

        Next I

        End With

End Sub

找到零件的代码部分有效,但复制和粘贴的两行不起作用。

当我运行代码时,它确实激活了“BOM”表,我可以看到程序激活了从第四列和第二行开始到第 29 行的单元格,因此这表明转置部分有效,但我没有看到任何值。单元格只是空白。

标签: excelvba

解决方案


...找到特定设备并复制其相应零件...

该声明似乎表明只有一件设备可以从 COMP 工作表复制到 BOM 工作表。

Sub COMP_PARTS()

    dim COMP1 as string, I as long, II as long

    COMP1 = "EQUIPMENT 1"
    II = 30  '2 to 29 is a total of 30 inclusive cells

    'reference the source named range
    With Worksheets("COMP").Range("COMP_range")

        'Cycle through the rows in column A of the named range
        For I = 1 To .Rows.Count

            'check if the first column in Range("COMP_range") is COMP1
            If .Cells(I, 1) = COMP1 Then

                'reference the total source of the data to transfer
                with .Cells(I, 2).Resize(1, II)
                    'Resize the Target to match the transposed size of the source
                    'Offset the top-left cell of the target here for multiple sources
                    ThisWorkbook.Sheets("BOM").Cells(2, 4).Resize(.Columns.Count, .Rows.Count).OFFSET(0, 0) = _
                        application.transpose(.Value)

                    'If only one, then no need to continue
                    Exit For

                end with

            End If

        Next I

    End With

End Sub

如果可能有多个设备数据集,请删除Exit For并使用递增的整数变量来偏移目标位置。


推荐阅读