2016-06-09 149 views
1

無論我做什麼,我都無法讓這個錯誤消失。這個當前版本的代碼是爲了完整地說明每個引用。 「BOM組件的設置範圍」行後出現錯誤。大多數主題指出,使用.Range(Cells())而不指定單元格的位置將導致此錯誤,但我已經完成了完整的矯枉過正的引用,因此我不確定它爲什麼仍然出錯。這裏也只有一個工作簿。VBA錯誤1004設置範圍相等

@Scott Craner @BruceWayne我終於明白了; Oracle報告以一種非常漂亮的格式出現,並且循環中的第一張表格導致範圍實際上不相等。一旦我刪除了它,它就完美地運行了。

 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 

回答

1

哇 - 首先檢查範圍是否相同。然後,我強烈建議爲表格名稱和範圍使用一些變量:

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 

這是否有助於解決您的問題?

+2

「Set ...」語句中的那些「.Values」不應該被刪除嗎? – user3598756

+0

@ user3598756 - 哦,你說的沒錯。我已更新該帖子。 – BruceWayne

+1

不會upvoting這個,直到你的代表改變從'6666' = P(通過XD提醒我) – findwindow

0

的問題是在這裏:

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} 
1

您使用

ActiveWorkbook 

要設置環路電流片

然後

ThisWorkbook 
在複製/粘貼值聲明

說錯誤

那麼它可能是你從運行宏工作簿(ThisWorkbook)從當前活動的一個(ActiveWorkbook),其工作表您通過

循環在這種情況下只是改變ThisWorkbookActiveWorkbook

不同
+0

好點,可以將其設置爲一個變量來保存一些輸入。 – BruceWayne

相關問題