0

我有这项工作需要在 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 
4

1 回答 1

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
于 2012-12-18T13:19:56.660 回答