vba 使用数据创建、命名和填充新工作簿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5427253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:53:48  来源:igfitidea点击:

Create, name, and populate new workbook with data

excelvbaexcel-vba

提问by AJ Eman

I have an Excel sheet with two columns of data. Column A has the desired new workbook names and Column B's adjacent cell has the data I want in the new work book.

我有一个包含两列数据的 Excel 工作表。A 列具有所需的新工作簿名称,B 列的相邻单元格具有我想要的新工作簿中的数据。

So if 032411is in column A and 50is in column B then the macro would create a new workbook named 032411and 50would be in cell A1of that workbook.

因此,如果032411在 A 列中并且50在 B 列中,则宏将创建一个名为的新工作簿03241150并将位于A1该工作簿的单元格中。

回答by Tiago Cardoso

You can use this:

你可以使用这个:

Sub CreateBooks()

    Dim oCell As Excel.Range
    Dim oWorkbook As Excel.Workbook

    'Added to avoid messages asking to confirm overwriting
    '   previous existent files with same name

    Application.DisplayAlerts = False

    For Each oCell In Range("A:A")

        If oCell.Value = "" Then Exit For

        Set oWorkbook = Workbooks.Add

        oWorkbook.Sheets(1).Cells(1, 1).Value = oCell.Offset(0, 1).Value

        'If the cell value contains only the file name (instead of the whole path
        '   the file needs to be saved) it will save into MyDocuments folder
        oWorkbook.Close True, oCell.Value

    Next oCell

    Application.DisplayAlerts = True

End Sub

In case you have several files to generate, you can alternatively use the application.ScreenUpdating = False.

如果要生成多个文件,也可以使用application.ScreenUpdating = False.