10

我正在尝试将活动工作表的内容复制到新工作簿。

Sub new_workbook()

    Dim ExtBk As Workbook
    Dim ExtFile As String

    Columns("A:N").Copy

    Workbooks.Add.SaveAs Filename:="output.xls"
    ExtFile = ThisWorkbook.Path & "\output.xls"

    Set ExtBk = Workbooks(Dir(ExtFile))
    ExtBk.Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    Application.DisplayAlerts = False
    ExtBk.Save
    Application.DisplayAlerts = True

End Sub

我在PasteSpecial主题指定的错误所在的行收到错误。我有点困惑,因为如果我将它定向到源工作簿,它就可以工作。

也许我需要使用 Windows(output.xls)?

4

4 回答 4

17

Copy如果您只关心保存值,则根本不要使用方法。

Sub new_workbook()
Dim wbMe As Workbook: Set wbMe = ThisWorkbook
Dim ws As Worksheet: Set ws = wbMe.ActiveSheet
Dim ExtBk As Workbook

Set ExtBk = Workbooks.Add
ExtBk.SaveAs Filename:=wbMe.Path & "\output.xls"

ExtBk.Worksheets("Sheet1").Range("A:N").Value = ws.Range("A:N").Value

Application.DisplayAlerts = False
ExtBk.Save
Application.DisplayAlerts = True

End Sub

注意:如果您的未保存,这将失败(之前的代码也会失败)ThisWorkbook

于 2013-06-24T18:40:04.000 回答
2

我让它工作:

Sub cp2NewWb()
    Dim ExtFile As String
    ExtFile = ThisWorkbook.Path & "output.xls"
    Workbooks.Add.SaveAs Filename:="output.xls"

    Windows("test1.xlsm").Activate
    Range("A1:AA100").Copy
    Windows("output.xls").Activate
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
    Worksheets(Worksheets.Count).Columns("A:AA").EntireColumn.AutoFit
    Range("A1").Select

    Windows("test1.xlsm").Activate
    Application.CutCopyMode = False
    Range("A1").Select
End Sub

我需要在激活窗口之间执行此操作,否则它不起作用。

于 2013-06-24T19:06:22.387 回答
1

如果要复制整个区域,请复制工作表:

Worksheets("Sheet1").Copy Workbooks(2).Worksheets(1)

如果它复制了一些您不需要的列,那么您可以在之后将其删除。

如果要从 .xlsx 复制到 .xls,则需要使用复制/粘贴:

Worksheets("Sheet1").UsedRange.Copy Workbooks(2).Worksheets(1).Range("A1")

如果需要粘贴值:

Workbooks(2).Worksheets(1).UsedRange.Copy
Workbooks(2).Worksheets(1).Range("A1").PasteSpecial xlPasteValues

请注意,UsedRange除非此单元格包含某些内容,否则不会从 A1 开始。在这种情况下,您必须定义一个Range从 A1 开始并延伸到最后使用的单元格的对象。

于 2013-06-24T18:27:43.727 回答
0
Private Sub ExceltoExcel()
    Application.DisplayAlerts = False
    Application.EnableEvents = False
    'Input Data
     Sheets("Sheet1").Cells(1, 1).Select
     col = Sheets("Sheet1").Cells(2, 2)
     Dim exlApp As Excel.Application
     Dim ExtBk As Excel.Workbook
     Dim exlWs As Excel.Worksheet
     ExtFile = ThisWorkbook.Path & "\output.xls"
     Set exlApp = CreateObject("Excel.Application")
     Set ExtBk = exlApp.Workbooks.Open(ExtFile)
     Set exlWs = exlWb.Sheets("Sheet1")
     ExtBk.Activate
     exlWs.Cells(2, 2) = col
     'Output Data
     exlWs.Range("A1").Select
     exlWb.Close savechanges:=True
     Set ecxlWs = Nothing
     Set exlWb = Nothing
     exlApp.Quit
     Set exlApp = Nothing
     Application.EnableEvents = True
     Application.DisplayAlerts = True
End Sub
于 2013-06-24T18:23:28.217 回答