我正在尝试打开文本文件并将其复制并粘贴到我的数据表中。但是,我似乎无法使它工作(我看到一个对象需要错误)。有什么帮助吗?谢谢
Sub Bam2()
Dim FilesToOpen
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim newSheet As Worksheet
Dim targetSheet As Worksheet, sourceSheet As Worksheet
Dim customerWorkbook As Workbook, targetWorkbook As Workbook
Set targetWorkbook = Application.Workbooks("Book1.xlsm")
Set targetSheet = targetWorkboook.Sheets("Data")
targetSheet.Range("A1:M5000").ClearContents
FilesToOpen = Application.GetOpenFilename(Title:="Text Files to Open")
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen, Format:=4)
wkbTemp.Sheets(1).Cells.Copy
targetSheet.Range("A1").PasteSpecial xlPasteValues
Application.CutCopyMode = 0
wkbTemp.Close
End Sub
答案 0 :(得分:1)
猜测
Set targetWorkbook = Application.Workbooks("Book1.xlsm")
如果您刚刚创建了一个名为Book1的工作簿 - 它不会被称为Book1.xlsm,除非您实际上已将其保存在该名称下。尝试
Set targetWorkbook = Application.Workbooks("Book1")
答案 1 :(得分:0)
执行此操作时确实有效,但如何选择仅复制特定范围内的一列,而不是整个文件?
Sub Bam()
Dim FilesToOpen
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim newSheet As Worksheet
FilesToOpen = Application.GetOpenFilename(Title:="Text Files to Open")
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen, Format:=4)
wkbTemp.Sheets(1).Cells.Copy
Set newSheet = ThisWorkbook.Sheets("Data")
With newSheet
.PasteSpecial
End With
Application.CutCopyMode = False
wkbTemp.Close
End Sub