我需要在VBA中完成这项工作,如果我打开IDE并从那里运行代码,所有操作都按预期运行,将数据从txt文件加载到新的临时工作簿,复制并粘贴到我的工作表,关闭临时工作簿。
但是当使用快捷方式运行时,即Ctr + Sft + L,它会将数据加载到临时工作簿,激活它并在那里停止执行...不会将数据粘贴回工作表。我该如何解决这个问题?
以下是代码:
Sub Load_Text()
Dim wsSheet As Worksheet
InsertWorkSheet ("Data")
Set wsSheet = ThisWorkbook.Sheets("Data")
Workbooks.OpenText Filename:="C:\Documents and Settings\w059\Desktop\20121107_Report.txt", _
Origin:=xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, Comma:=False, _
Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), _
Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1)), TrailingMinusNumbers:=True
ActiveWorkbook.Worksheets(1).Cells.Copy wsSheet.Range("A1")
ActiveWorkbook.Close True
End Sub
Public Sub InsertWorkSheet(name As String)
Dim wsSheet As Worksheet
On Error Resume Next
Set wsSheet = ThisWorkbook.Sheets(name)
If wsSheet Is Nothing Then
ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ThisWorkbook.Sheets(Sheets.Count).name = name
End If
End Sub
答案 0 :(得分:0)
我得到了对ActiveWorkbook的错误引用。这纠正了它:
代替
ActiveWorkbook.Worksheets(1).Cells.Copy wsSheet.Range("A1")
ActiveWorkbook.Close True
使用
Dim wb As Workbook
Set wb = ActiveWorkbook
wb.Worksheets(1).Cells.Copy wsSheet.Range("A1")
wb.Close True