打开CSV并复制

时间:2016-03-15 12:42:00

标签: excel vba excel-vba 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

1 个答案:

答案 0 :(得分:4)

试着看看这个。我从你的副本和粘贴部分代码中删除了thisWB和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