VBA数据从一个工作簿传输到另一个工作簿,数据类型不匹配错误

时间:2013-12-27 17:58:30

标签: excel vba

我是VBA的新手,但学习。我自己编写了以下大部分代码,其中一些代码是继承的。我的目标是遍历多个文本文件(这些文件各自包含一组唯一的原始数据)并将这些数据复制(或以其他方式传输)到我已经制作的分析模板中,然后将其“保存为”与原始数据文本文件具有相同的文件名。我已经工作了好几天了,已经做了大量的搜索以实现这一点,但是,我目前仍然遇到“运行时类型'13'错误 - 不匹配数据类型”我不知道了解所以我不知道如何克服它。错误是@“Data.Sheets(Sheet1).Range(”A1:G180000“)。复制。如果我注释掉上述行和后面的行并使用上面的行(”Template.Sheets(Sheet1)。范围(“A1:G180000”)。值......“)我仍然得到同样的错误。我的代码发布在下面,非常感谢任何帮助。谢谢:)

Sub Shift_Load_Data_Plotter_Template()

'Josh Smith
'12/27/2013
'Shift Load Data Plotter Template
'This macro will bring up the Open dialog box so you can open multiple text files and analyze them using the Shift Load Data Plotter Template

'Brings up the Open window so you can select multiple excel files to import
    Dim fn As Variant, f As Integer
    Dim FileName As String
    'Data is the source workbook and Template is the destination workbook
    Dim Data As Workbook
    Dim Template As Workbook

    fn = Application.GetOpenFilename("Text files,*.txt", _
    1, "Select One Or More Files To Open", , True)
    If TypeName(fn) = "Boolean" Then Exit Sub
    'the line below was modified from from just "workbooks.open "Z:\..." to "Set Template = Workbooks.open..."
    'opens the Shift Load Data Analyzer Template workbook and sets the "Template" variable equal to said workbook
    Set Template = Workbooks.Open("Z:\General Reference, Tools\Shift Load Data Analyzer Template.xlsx")


    For f = 1 To UBound(fn)
    'the line below was modified from just "workbooks.open fn(f)" to what it shows now
    'sets the "Data" variable equal to the workbook which contains the data from the text file
    Set Data = Workbooks.Open(fn(f))
    FileName = ActiveWorkbook.Name
    'Data.Activate



    'Template.Sheets(Sheet1).Range("A1:G180000").Value = Data.Sheets(Sheet1).Range("A1:G180000").Value

    Data.Sheets(Sheet1).Range("A1:G180000").Copy
    Template.Sheets(Sheet1).Range("A1").PasteSpecial (xlPasteValues)


    'the line below used to be "ActiveWorkbook.SaveAs..."
    Template.SaveAs FileName:="Z:\" & FileName & ".xlsx"

    Data.Close


    Next f

End Sub

2 个答案:

答案 0 :(得分:1)

该行:

Data.Sheets(Sheet1).Range("A1:G180000").Copy

应该如下所示:

Data.Sheets( “工作表Sheet”)范围。( “A1:G180000”)。复制

如果您要引用名称,则表格名称周围需要引号(Sheets()函数正在查找您在Excel中的选项卡上看到的工作表名称,而不是Sheet1,Sheet2,Sheet3等。在VBA屏幕中看到)。否则你可以这样写:

Data.Sheet1.Range("A1:G180000").Copy

答案 1 :(得分:0)

尝试将其更改为:

    Data.Sheets(1).Range("A1:G180000").Copy
    Template.Sheets(1).Range("A1").PasteSpecial (xlPasteValues)