【问题标题】:Open CSV and copy打开 CSV 并复制
【发布时间】:2016-03-15 12:41:59
【问题描述】:

我正在尝试打开一个 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

【问题讨论】:

    标签: vba excel csv


    【解决方案1】:

    试着看看这个。我从您复制和粘贴部分代码中删除了 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
    

    【讨论】:

    • 虽然您在这里提到的亲子关系是正确的,但直接复制也可以正常工作,试试这行:thatWS.Range("A1:G150").Copy Destination:= thisWS.Range("A1") 要清楚,PasteSpecial 方法也可以工作。只是没有必要。
    • 谢谢你们。两种解决方案都能正常工作。我将 Lubos 标记为正确,但 Scott 的效果同样出色。
    猜你喜欢
    • 2021-03-11
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 2018-07-04
    • 1970-01-01
    • 2015-08-15
    • 2020-06-01
    相关资源
    最近更新 更多