VBA错误1004设置范围等于

不pipe我做什么,我都不能让这个错误消失。 这个当前版本的代码是为了完整地说明每个引用。 “BOM组件设置范围”行后出现错误。 大多数的话题指出,使用.Range(Cells())而不指定单元格的位置将导致这个错误,但是我已经完成了整个引用的过度操作,所以我不确定它为什么仍然出错。 这里也只有一个工作簿。

@Scott Craner @BruceWayne我终于明白了; 甲骨文的报告出现在一个非常漂亮的格式,循环中的第一张表导致范围实际上是不平等的。 只要我删除该表,它运行完美。

Sub Macro3() ' ' Macro3 Macro ' ' Keyboard Shortcut: Ctrl+c ' Dim ws As Worksheet Dim lastRow As Integer Dim summaryRow As Integer Dim currentSheetRows As Integer Dim i As Integer Dim j As Integer summaryRow = 2 For Each ws In ActiveWorkbook.Worksheets If ws.Range("L3") = "" Then currentSheetRows = ws.Cells(ws.Rows.Count, "F").End(xlUp).Row i = summaryRow j = summaryRow 'set range for item # and item UOM' For j = summaryRow To (summaryRow + (currentSheetRows - 3)) Sheets("Summary").Cells(j, 1).Value = ws.Cells(2, 1).Value Next j For i = summaryRow To (summaryRow + (currentSheetRows - 3)) Sheets("Summary").Cells(i, 2).Value = ws.Cells(2, 1).Value Next i 'set range for BOM components' ThisWorkbook.Worksheets("Summary").Range(ThisWorkbook.Worksheets("Summary").Cells(summaryRow, 3), ThisWorkbook.Worksheets("Summary").Cells((summaryRow + (currentSheetRows - 3)), 6)).Value = ThisWorkbook.Worksheets(ws.Name).Range(ThisWorkbook.Worksheets(ws.Name).Cells(3, 6), ThisWorkbook.Worksheets(ws.Name).Cells(currentSheetRows, 9)).Value summaryRow = summaryRow + currentSheetRows End If Next ws End Sub 

哇 – 首先,检查范围是相同的大小。 然后,我强烈build议为表格名称和范围使用一些variables:

 Sub t() Dim summaryWS As Worksheet Dim otherWS As Worksheet Set summaryWS = ThisWorkbook.Sheets("Summary") Set otherWS = ThisWorkbook.Worksheets(ws.Name) Dim copyRng As Range, pasteRng As Range With summaryWS Set copyRng = .Range(.Cells(SummaryRow, 3), .Cells((SummaryRow + (currentSheetRows - 3)), 6)) End With With otherWS Set pasteRng = .Range(.Cells(3, 6), .Cells(currentSheetRows, 9)) End With pasteRng.Value = copyRng.Value End Sub 

这有助于你的问题吗?

你正在使用

 ActiveWorkbook 

设置循环当前表单

接着

 ThisWorkbook 

在复制/粘贴值声明中出现错误

这可能是( ThisWorkbook )运行macros的工作簿不同于当前活动的工作簿( ActiveWorkbook ),它的循环工作表

在这种情况下,只需将ThisWorkbook更改为ActiveWorkbook

问题在这里:

ThisWorkbook.Worksheets("Summary").Range(ThisWorkbook.Worksheets("Summary").Cells(summaryRow, 3), ThisWorkbook.Worksheets("Summary").Cells((summaryRow + (currentSheetRows - 3)), 6)).Value = ThisWorkbook.Worksheets(ws.Name).Range(ThisWorkbook.Worksheets(ws.Name).Cells(3, 6), ThisWorkbook.Worksheets(ws.Name).Cells(currentSheetRows, 9)).Value

下标超出范围。

尝试

 With Sheets(ws.name) .Cells({var},{var}).Value = {var}