VBA Runtime error 1004 when trying to access range of sheet

旧城冷巷雨未停 提交于 2019-12-10 17:52:46

问题


I am building a small vba script that is merging tables from several workbook into one single worksheet of another workbook. The error is raised when I try to set the destination range's value:

wksPivotData.Range(wksPivotData.Cells(CurrentRow, 1)).Resize(tbl.ListRows.Count, tbl.ListColumns.Count).Value = _
    tbl.Range.Value

The error: "Run-time error '1004': Application-Defined or object-defined error"

I went through similar questions, and the general answer is what I found in this one: The selected cell belongs to another worksheet than the one desired.

While this makes complete sense, I still can't figure why my code breaks as I'm only using numerical reference (CurrentRow is a Long) and Resize, which should prevent me from doing such a mistake.

Additionally, I ran a couple quick tests in the Immediate window and it turns out that while the worksheet wksPivotData exists and I can access its name and a cell value, the range function simply doesn't work:

Debug.Print wksPivotData.Name
    PivotData

Debug.Print wksPivotData.Cells(1, 1).Value
    123

Both of those work but the next one doesn't:

Debug.Print wksPivotData.Range(1, 1).Value

回答1:


Your last line, Debug.Print wksPivotData.Range(1, 1).Value won't print because you're misuing Range(). I assume you want A1?

When using Range(1,1), you're referring to a non-existent range. If you want to do cell A1, you need

With wksPivotData
   myData = .Range(.Cells(1,1),.Cells(1,1)).Value
End with

Since you're using multiple worksheets, I'd use the with statement as above. Another way to write the same thing is wksPivotData.Range(wksPivotData.Cells(1,1),wksPivotData.Cells(1,1)) (You need to explicitly tell Excel what sheet you want to refer to when using Range() and cells().

Finally, for your resize, if I recall correctly, you're going to have to add the same Cell() twice in your range:

wksPivotData.Range(wksPivotData.Cells(CurrentRow, 1),ksPivotData.Cells(CurrentRow, 1)).Resize(tbl.ListRows.Count, tbl.ListColumns.Count).Value = _
    tbl.Range.Value

Or, for the same thing, but different way of doing it:

With wksPivotData
    .Range(.Cells(currentRow, 1), .Cells(currentRow, 1)).Resize(tbl.ListedRows.Count, tbl.ListColumns.Count).Value = tbl.Range.Value
End With


来源:https://stackoverflow.com/questions/32129567/vba-runtime-error-1004-when-trying-to-access-range-of-sheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!