【发布时间】:2013-12-27 17:58:29
【问题描述】:
我是 VBA 新手,但正在学习。我自己编写了以下大部分代码,其中一些是继承的。我的目标是遍历多个文本文件(每个都包含一组独特的原始数据)并将该数据复制(或以其他方式传输)到我制作的分析模板中,然后将其“另存为”具有与原始数据文本文件相同的文件名。我已经为此工作了好几天,并且已经进行了大量搜索以达到这一点,但是,我目前遇到了“运行时类型'13'错误 - 数据类型不匹配”,我没有'不明白,所以我不知道如何克服它。错误是@"Data.Sheets(Sheet1).Range("A1:G180000").Copy。如果我注释掉上述行及其后面的行并使用上面的行 ("Template.Sheets(Sheet1). Range("A1:G180000").Value...") 我仍然得到同样的错误。我的代码发布在下面,非常感谢任何帮助。谢谢:)
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
【问题讨论】:
-
你在哪一行得到错误?
-
如果您只想复制值而不是格式,则 pior 逻辑会更好,即
'Template.Sheets(Sheet1).Range("A1:G180000").Value = Data.Sheets(Sheet1).Range("A1:G180000").Value