我是VBA的新手,并且一直在使用该网站拼凑出一个解决方案。
我需要编写一个提示用户打开文件(wb2)的宏,从该工作簿中的Sheet1复制一行数据(wb2),然后将其粘贴到原始工作簿中的下一个空行(wb) )也在Sheet1上。我得到了它,直到我尝试在下一个空行添加粘贴代码 - 我现在收到以下错误消息,“运行时错误'438':对象不支持此属性或方法”
非常感谢任何帮助。
Sub test()
Dim wb As Workbook, wb2 As Workbook
Dim ws As Worksheet
Dim vFile As Variant
'Set source workbook
Set wb = ActiveWorkbook
'Open the target workbook
vFile = Application.GetOpenFilename("Excel-files,*.xlsx", _
1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
'Set selectedworkbook
Set wb2 = ActiveWorkbook
wb2.Range("A3:E3").Select
Selection.Copy
wb.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Application.CutCopyMode = False
Application.ScreenUpdating = True
wb2.Close
'Set targetworkbook
Set wb = ActiveWorkbook
End Sub
答案 0 :(得分:6)
关于这个主题的简短说明: 而不是
wb2.Worksheets("Output").Range("J3:R3").Select
Selection.Copy
试
wb2.Worksheets("Output").Range("J3:R3").Copy
另外 而不是
wb.Worksheets("Master").Range("C" & LastCellRowNumber).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
试
wb.Worksheets("Master").Range("C" & LastCellRowNumber).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
通常,Select
会产生无法解释的错误。特别是在处理多个工作簿时,请尽量远离Select
。这段代码几乎直接来自我的工作代码。如果这不能解决问题,请告诉我们。
答案 1 :(得分:2)
我重新编写代码并使其正常工作。这可能不是最干净的方式,但考虑到我的时间表和缺乏VBA知识,它必须这样做。
非常感谢工程师们的帮助。
描述:此代码应放入要从其他工作簿粘贴内容的工作表中。当它运行时,它将提示您打开要从中复制的工作簿(“输出”工作表),然后它将选择您在代码中指定的单元格(JR:R3),从初始的下一个空行开始粘贴它们工作簿(在“主”工作表中查找C列的最后一行),然后它将关闭&保存刚刚复制的工作簿。
Sub CommandButton1_Click()
'Last cell in column
Dim WS As Worksheet
Dim LastCell As Range
Dim LastCellRowNumber As Long
Set WS = Worksheets("Master")
With WS
Set LastCell = .Cells(.Rows.Count, "C").End(xlUp)
LastCellRowNumber = LastCell.Row + 1
End With
Dim wb As Workbook, wb2 As Workbook
Dim vFile As Variant
'Set source workbook
Set wb = ActiveWorkbook
'Open the target workbook
vFile = Application.GetOpenFilename("Excel-files,*.xlsx", _
1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
'Set selectedworkbook
Set wb2 = ActiveWorkbook
'Select cells to copy
wb2.Worksheets("Output").Range("J3:R3").Select
Selection.Copy
'Go back to original workbook you want to paste into
wb.Activate
'Paste starting at the last empty row
wb.Worksheets("Master").Range("C" & LastCellRowNumber).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Application.ScreenUpdating = True
'Close and save the workbook you copied from
wb2.Save
wb2.Close
End Sub
答案 2 :(得分:0)
你试过这个吗?
Selection.Copy
wb.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select
Selection.PasteSpecial xlPasteValues