打开CSV并复制

朋友,我试图每天打开一个CSV文件(每天从另一个程序生成),并将CSV表格中的数据复制到当前工作簿中的某个工作表中。 我已经在这段代码上工作了一段时间,我认为这是非常接近正确的,但我一直在我的复制/粘贴线上运行时错误438。 任何帮助?

谢谢!

这是我的代码:

Sub GetCSV() Dim thatWB As Workbook, thisWB As Workbook Dim thisWS As Worksheet, thatWS As Worksheet Dim zOpenFileName As String Dim inputData As String 'get name of sheet to open inputData = InputBox("Enter name of file") 'open CSV file zOpenFileName = Application.GetOpenFilename 'error handling If zOpenFileName = "" Then Exit Sub Application.ScreenUpdating = False Set thisWB = ThisWorkbook 'destination workbook Set thisWS = Sheets("f_dump") 'destination worksheet Set thatWB = Workbooks.Open(zOpenFileName) 'source CSV Set thatWS = thatWB.Sheets(inputData) 'source worksheet Application.CutCopyMode = False thatWB.thatWS.Range("A1:G150").Copy Destination:=thisWB.thisWS.Range("A1") thatWB.Close End Sub 

试着看看这个。 我从你的副本和粘贴部分代码中删除了这个WB和ThatWB,因为它是第一个问题的来源(并且我将工作簿规范移动到了表单声明中)。

然后下一个问题是粘贴。 我不知道为什么,但是当调用范围,你需要使用PasteSpecial(在Excel中的VBA是有点神奇,而不是编程/脚本)

 Sub GetCSV() Dim thatWB As Workbook, thisWB As Workbook Dim thisWS As Worksheet, thatWS As Worksheet Dim zOpenFileName As String Dim inputData As String 'get name of sheet to open inputData = InputBox("Enter name of file") 'open CSV file zOpenFileName = Application.GetOpenFilename 'error handling If zOpenFileName = "" Then Exit Sub Application.ScreenUpdating = False Set thisWB = ThisWorkbook 'destination workbook Set thisWS = ThisWorkbook.Sheets("Sheet1") 'destination worksheet Set thatWB = Workbooks.Open(zOpenFileName) 'source CSV Set thatWS = thatWB.Sheets(inputData) 'source worksheet Application.CutCopyMode = False thatWS.Range("A1:G150").Copy thisWS.Range("A1:G150").PasteSpecial xlPasteAll thatWB.Close End Sub