简体   繁体   English

Excel VBA宏-范围类的复制方法失败&范围类的插入方法失败

[英]Excel VBA Macro - Copy method of range class failed & Insert method of range class failed

I've written a macro to copy and insert rows or columns in different locations depending on an input string. 我编写了一个宏,用于根据输入字符串在不同的位置复制和插入行或列。 The copy and insert locations are defined by Named Ranges within the spreadsheet. 复制和插入位置由电子表格中的“命名范围”定义。

If I want to add several columns in the same section, everything works great. 如果我想在同一部分中添加几列,那么一切都很好。 If I add even one column in one section, then want to add a column in another section, I get one of two errors: Copy method of Range class failed OR Insert method of Range class failed 如果我在一个部分中甚至添加了一个列,然后又想在另一部分中添加一列,则会出现两个错误之一: Range类的复制方法失败Range类的 插入方法失败

I haven't been able to figure out why sometimes the copy method throws an error and sometimes it doesn't. 我一直无法弄清楚为什么有时候复制方法会引发错误,有时却不会。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Code: 码:

    Sheets("TL Master").Range("Insert" & strAddType).Copy

        'Offset for row/column
        If strRowColumn = "row" Then
            'Row = add value above
            Range("Insert" & strAddType).Insert Shift:=xlDown
            Range("Add" & strAddType & "ButtonCell").Offset(-4, 0).Value = strNewName
        Else
            'Column = add value left
            Sheets("TL Master").Range("Insert" & strAddType).Insert Shift:=xlToRight
            Range("Add" & strAddType & "ButtonCell").Offset(0, -4).Value = strNewName
            If strAddType = "Machine" Then Range("Add" & strAddType & "ButtonCell").Offset(0, -4).Interior.Color = clrComplexityColor

        End If

You code is missing the sheet name. 您的代码缺少工作表名称。 For example - 例如 -

Sheets("TL Master").Range("Insert" & strAddType).Copy

    'Offset for row/column
    If strRowColumn = "row" Then
        'Row = add value above
        Sheets("TL Master").Range("Insert" & strAddType).Insert Shift:=xlDown
        Sheets("TL Master").Range("Add" & strAddType & "ButtonCell").Offset(-4, 0).Value = strNewName
    Else
        'Column = add value left
        Sheets("TL Master").Range("Insert" & strAddType).Insert Shift:=xlToRight
        Sheets("TL Master").Range("Add" & strAddType & "ButtonCell").Offset(0, -4).Value = strNewName
        If strAddType = "Machine" Then Range("Add" & strAddType & "ButtonCell").Offset(0, -4).Interior.Color = clrComplexityColor

    End If

The other thing I would make note of is if your Offset forces data to be pasted outside of the sheet this will cause an error. 我要注意的另一件事是,如果您的“偏移量”将数据粘贴到图纸之外,则将导致错误。 For example, if your named range is A1:A10 and you do and Offset(0, -1) this is off the sheet and causes an error. 例如,如果您的命名范围是A1:A10,并且您执行了Offset(0,-1),则这不在工作范围内并导致错误。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM