将活动工作表中的值复制到新的Excel文件中

时间:2014-06-25 14:51:27

标签: excel vba excel-vba

我有一张名为Final_Sheet的工作表,我想在该工作表上创建一个按钮并执行以下操作

选择单元格区域A1:D30并从单元格中拾取值并创建一个新的Excel文件,并将复制的单元格值粘贴到已创建的Excel文件的Sheet1中。我能够做到这一点,进一步我无法理解该做什么可以请任何人帮助我?

Private Sub Button1_Click()
Dim rownum As Integer
Dim selection As Range

On Error Resume Next
Application.ScreenUpdating = False
Application.DisplayAlerts = False

rownum = InputBox("Row No to Copy :", "OK")
selection = ActiveSheet.Range(Cells(1, 1), Cells(rownum, 10)).Select
selection.Copy


Flname = InputBox("Enter File Name :", "Creating New File...")

MsgBox ("Output File Created Successfully")
If Flname <> "" Then
    Set NewWkbk = Workbooks.Add
    ThisWorkbook.Sheets(1).Range("D1:D30").Copy Before:=NewWkbk.Sheets(1)
    NewWkbk.Sheet(1).Select
    Cells(1, 1).Activate
    selection.PasteSpecial xlPasteValues

    NewWkbk.SaveAs ThisWorkbook.Path & "\" & Flname

    ActiveWorkbook.Close
End If

End Sub

1 个答案:

答案 0 :(得分:0)

以下代码应该按照您的要求执行。

编辑:仅粘贴值

Private Sub Button1_Click()
    'Dim Variables
    Dim ws As Worksheet
    Dim rng As Range
    Dim wbNew As Workbook, wbCurrent As Workbook
    Dim strFileName As String

    'Assign object variables
    Set wbCurrent = ActiveWorkbook
    Set ws = wbCurrent.ActiveSheet
    Set rng = ws.Range("A1:D30") 'Amend range if needed

    'Get desired file path from user
    strFileName = InputBox("Enter File Name: ", "Creating New File...")
    If strFileName <> "" Then
        'Create new Workbook and paste rng into it
        Set wbNew = Workbooks.Add
        rng.Copy
        wbNew.Sheets(1).Range("A1:D30").PasteSpecial xlValues

        'Save new workbook using desired filepath
        wbNew.SaveAs wbCurrent.Path & "\" & strFileName
    End If
End Sub

关于您希望使用ActiveWorkbook.Close关闭哪个工作簿的问题,我不清楚,但您可以轻松地在wbNew.Close下面添加wbCurrent.ClosewbNew.SaveAs ...作为必需的。