VBA运行时错误1004“应用程序定义或对象定义的错误”与范围

这是我第一次自己写macros,遇到两个小问题。

macros的任务:将一个文档的信息复制到特定列中的另一个文档中,如果该列是空的,在这种情况下它应该使用下一列。

这是迄今为止的代码:

Sub CopyData() Dim i As Long Dim wbA As Workbook Dim wbN As Workbook Dim Filepath As String i = 7 Set wbA = ThisWorkbook Filepath = "C:\Users\sebastian\Desktop\assessment answers" Do If IsEmpty(wbA.Sheets("Answers").Cells(1, i)) Then Set wbN = Workbooks.Open(Filepath) If Cells(37, 3).Value = 31 Then wbN.Sheets("Answers").Range(Cells(37, 4), Cells(46, 4)).Copy _ Destination:=wbA.Sheets("Answers").Range(Cells(36, i), Cells(45, i)) ElseIf Cells(37, 3).Value = 41 Then wbN.Sheets("Answers").Range(Cells(37, 4), Cells(46, 4)).Copy _ Destination:=wbA.Sheets("Answers").Range(Cells(46, i), Cells(55, i)) ElseIf Cells(37, 3).Value = 51 Then wbN.Sheets("Answers").Range(Cells(37, 4), Cells(46, 4)).Copy _ Destination:=wbA.Sheets("Answers").Range(Cells(56, i), Cells(65, i)) Else MsgBox "There could be a problem with the data, please check if the candidate has selected a topic." Exit Sub End If wbN.Sheets("Answers").Range(Cells(2, 4), Cells(3, 4)).Copy _ Destination:=wbA.Sheets("Answers").Range(Cells(1, i), Cells(2, i)) wbN.Sheets("Answers").Range(Cells(7, 4), Cells(36, 4)).Copy _ Destination:=wbA.Sheets("Answers").Range(Cells(6, i), Cells(35, i)) wbN.Close Exit Sub Else i = i + 1 End If Loop End Sub 

1.问题(VBA运行时错误1004)发生在这里后: 如果单元格(37,3)。值= 31然后

如果我使用.Range("D37:D46")和其他单元格的范围,它正在工作,但我想增加与循环的列,当有数据已经​​填入。 你有解决这个问题的想法吗?

2.是否有方法来改变文件path,以便谁使用它,将被引导到文件应该位于的桌面?

 Filepath = "C:\Users\sebastian\Desktop\assessment answers" 

谢谢你的想法,

塞巴斯蒂安

错误号码1004通常意味着“我找不到你要找的东西”。

对于这个特定的例子,你看到这个错误,因为你没有足够的明确你的编码。 如果有的话,最好去OTT。

所以,而不是

 If Cells(37, 3).Value = 31 Then 

使用:

 If wbA.Sheets("Sheet Name Here").Cells(37, 3).Value = 31 Then 

更好的是在代码中包含“With”语句。 一个通用的例子如下:

  Sub Example() Dim wb As Workbook Dim sht As Worksheet Set wb = ActiveWorkbook Set sht = wb.ActiveSheet With sht .Name = "New Name" .Visible = xlSheetVisible .Protect End With End Sub 

这样可以节省大量的打字时间,并且可以在一次打击中为多个对象执行多个操作。

对于其他人,谁可能有兴趣,我发布我的解决scheme在这里:

问题1:

在Rory和Naing Win Htun的build议之后,我在小区前面加了一条路。 显然我可以用With来完成

 wbN.Sheets("Answers").Range(wbN.Sheets("Answers").Cells(37, 4), wbN.Sheets("Answers").Cells(46, 4)).Copy _ Destination:=wbA.Sheets("Answers").Range(wbA.Sheets("Answers").Cells(36, i), wbA.Sheets("Answers").Cells(45, i)) 

问题2:

用户现在可以手动input文件的path和名称,这显然是一个更好的解决scheme。 这也是Naing Win Htun提出的build议。

感谢大家的帮助。