【问题标题】:Excel VBA run-time Error '424' Object RequiredExcel VBA 运行时错误“424”需要对象
【发布时间】:2018-08-08 03:27:42
【问题描述】:

我遇到了一个问题,需要运行时错误“424”对象。 这是我从上一篇文章中获得的解决方案,经过一段时间的故障排除后,我仍然无法解决。感谢@rawrplus 的解决方案,我仍在学习 Excel vba。

链接: Excel VBA Cutting rows from workbook1 and paste it in workbook2

Option Explicit
Private Sub table_to_table()
'Declaration
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set wb1 = Workbooks.Open("C:\Documents and Settings\lye.yan.nian\My  Documents\testingmacro2.xlsx")
Set wb2 = Workbooks.Open("C:\Documents and Settings\lye.yan.nian\My Documents\testingmacro3.xlsx")
Set ws1 = wb1.Sheets("Test2")
Set ws2 = wb2.Sheets("Test1")

Dim res_lr As Long
Dim lr2 As Long
lr2 = ws2.Cells(Rows.Count, 2).End(xlUp).Row


MsgBox lr2   /* Testing is done as i can get this value */

Dim r As Range, ary
Set r = ws1.Application.Range(Cells(1, 2), Cells(1, 6)) /* Tested working as i can get this value too*/
ary = Application.Transpose(Application.Transpose(r.Value))
MsgBox Join(ary, " ")


Dim copyrange As Range
Dim i As Long /* This is declared */
For i = 2 To lr2

MsgBox i /* i did some testing on this and removed the below code */
Set copyrange = ws2.Application.Range(Cells(i, 2), Cells(i, 6)).Copy /* This is the part where i got the error i can't figure out why*/ 

res_lr = ws2.Cells(Rows.Count, 8).End(xlUp).Row
ws2.Range(Cells(res_lr, 8), Cells(res_lr, 12)).PasteSpecial xlPasteValues

Set copyrange = ws1.Application.Range(Cells(i, 2), Cells(i, 6)).Copy

ws2.Range(Cells(res_lr + 1, 8), Cells(res_lr + 1, 12)).PasteSpecial xlPasteValues

Next i

wb1.Close

End Sub

【问题讨论】:

  • 您需要使用他们所指的工作表来限定CellsRows,否则您将隐含使用ActiveSheet

标签: vba excel


【解决方案1】:
Set copyrange = ws2.Application.Range(Cells(i, 2), Cells(i, 6)).Copy

Range.Copy 不返回您可以分配给Range 对象变量的Range 对象引用。它是一个成员方法,它获取范围的内容,并将其复制到剪贴板中。

您的copyrange 不是.Copy 操作的结果,它是ws2.Application.Range(...) 调用的结果...格式错误。

这个可能修复它1

Set copyrange = ws2.Application.Range(Cells(i, 2), Cells(i, 6))
copyrange.Copy

....这就是你可能打算做的事情:

Set copyrange = ws2.Range(ws2.Cells(i, 2), ws2.Cells(i, 6))
copyrange.Copy

1 这是糟糕的代码,因为您有一个明确的 Worksheet 引用 (ws2),然后从那里您转到 Application 获取当前处于活动状态的任何工作表,然后继续工作那 - 所以你认为你正在处理ws2,而实际上你正在处理ActiveSheet目前碰巧是什么。与不合格的Cells 调用相同,隐式引用Application.ActiveSheet.Cells

【讨论】:

  • 非常感谢你,它成功了。现在我学到了一些东西,我将对我的代码进行更改,再次感谢您的建议。
  • Mathieu,你能再澄清一点吗?是不是很糟糕,因为使用Application.Range 绕过了工作簿对象和工作表对象,因此将在当前处于活动状态的工作表上选择范围?
  • @GMalc Application.Range 隐含为 Application.ActiveSheet.RangeRange 作为成员调用,始终是 Worksheet 对象的成员。好的代码使Worksheet 明确;-)
【解决方案2】:

尝试在引发错误的行添加单词set。 示例:set x = 'something

【讨论】:

  • "Set copyrange = ws2.Application.Range(Cells(i, 2), Cells(i, 6)).Copy" Set 已在此行使用
  • 我可以知道你在说什么括号吗?可以给我看看吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多