Workbooks.Add和Sheets.Add以及Workbooks.Open

一、Workbooks 对象的 Add 方法:新建工作簿,新建的工作簿将成为活动工作簿。语法是:

expression.Add(Template)

expression    : 必需。该表达式返回一个 Workbooks 对象。

Template    : Variant 类型,可选。确定如何创建工作簿。

1、如果本参数为指定一现有 Microsoft Excel 文件名的字符串,那么创建新工作簿将以该指定的文件作为模板。

2、如果本参数为常量,新工作簿将包含指定类型的单张工作表。可为以下 XlWBATemplate 常量之一:xlWBATChart、xlWBATExcel4IntlMacroSheet、xlWBATExcel4MacroSheet 或 xlWBATWorksheet。

3、如果省略本参数,Microsoft Excel 将创建包含一定数目的空白工作表的工作簿(该数目由 SheetsInNewWorkbook 属性设置)。

给出一个最常用也最常见的例子就是,本示例新建一个工作簿。

Workbooks.Add

二、Sheets 和 Worksheets 对象的 Add 方法:新建工作表、图表或宏表。新建的工作表将成为活动工作表。语法是:

expression.Add(Before, After, Count, Type)

expression     :    必需。该表达式返回上面的对象之一。

Before    :    Variant 类型,可选。指定工作表对象,新建的工作表将置于此工作表之前。

After    :    Variant 类型,可选。指定工作表对象,新建的工作表将置于此工作表之后。

Count    :    Variant 类型,可选。要新建的工作表的数目。默认值为 1。

Type    :    Variant 类型,可选。指定工作表类型。

1、Type 可为以下 XlSheetType 常量之一:xlWorksheet、xlChart、xlExcel4MacroSheet 或 xlExcel4IntlMacroSheet。

2、如果要基于现有模板插入工作表,则指定该模板的路径。

3、默认值为 xlWorksheet。

下面的示例是活动工作簿的最后一张工作表之前插入一个新的工作表。

ActiveWorkbook.Sheets.Add Before:=Worksheets(Worksheets.Count)

Workbooks 对象的 Open 方法:作用是打开一个工作簿。其语法为:

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

其中:

expression      必选。该表达式返回一个 Workbooks 对象。

FileName      String 类型,必需。要打开的工作簿的文件名。

UpdateLinks      Variant 类型,可选。指定文件中链接的更新方式。如果省略本参数,则提示用户选择链接的更新方式。否则,该参数的取值应为下表中的某个值。

值 含义
0 不更新任何引用。
1 更新外部引用,但不更新远程引用。
2 更新远程引用,但不更新外部引用。
3 同时更新远程引用和外部引用。

ReadOnly      Variant 类型,可选。如果该值为 True,则以只读模式打开工作簿。

Format      Variant 类型,可选。如果 Microsoft Excel 正在打开一个文本文件,则该参数用于指定分隔字符,如下表所示。如果省略本参数,则使用当前的分隔符。

值 分隔符
1 制表符
2 逗号
3 空格
4 分号
5 没有分隔符
6 自定义字符(请参阅 Delimiter 参数)

Password      Variant 类型,可选。该字符串指定打开一个受保护工作簿的密码。如果省略该参数并且指定工作簿已设置密码,则提示用户输入密码。

WriteResPassword      Variant 类型,可选。该字符串为一个写保护工作簿的写入权密码。如果省略该参数并且指定工作簿已设置密码,则提示用户输入密码。

IgnoreReadOnlyRecommended      Variant 类型,可选。如果该值为 True,则设置 Microsoft Excel 不显示建议只读消息(如果该工作簿以“建议只读”选项保存)。

Origin      Variant 类型,可选。如果该文件为文本文件,则该参数用于指示该文件来源于何种操作系统(以便正确映射代码页和回车/换行 (CR/LF))。可为以下 XlPlatform 常量之一:xlMacintosh、xlWindows 或 xlMSDOS。如果省略本参数,则使用当前操作系统。

Delimiter      Variant 类型,可选。如果该文件为文本文件并且 Format 参数为 6,则此参数用于指定用作分隔符的字符。例如,可使用 Chr(9) 代表制表符,使用“,”代表逗号,使用“;”代表分号或者使用自定义字符。如果该参数为字符串,则只使用该字符串的第一个字符。

Editable      Variant 类型,可选。如果该文件为 Microsoft Excel 4.0 加载宏,则该参数的值为 True 时可打开该加载宏以便在窗口中看到。如果该参数的值为 False 或者省略该参数,则该加载宏以隐藏方式打开,并且无法设为可见。本选项不能应用于由 Microsoft Excel 5.0 或更高版本的 Microsoft Excel 创建的加载宏。如果该文件是 Excel 模板,则参数的值为 True 时,会打开指定模板用于编辑。参数为 False 时,可根据指定模板打开新的工作簿。默认值为 False。

Notify      Variant 类型,可选。当该文件不能以可读写模式打开时,如果该参数的值为 True,则可将该文件添加到文件通知列表。Microsoft Excel 将以只读模式打开该文件并轮询文件通知列表,当文件通知列表中的该文件可用时通知用户。如果该参数的值为 False 或省略该参数,则不请求任何通知,并且不能打开任何不可用的文件。

Converter      Variant 类型,可选。打开文件时试用的第一个文件转换器的索引号。首先使用的是指定的文件转换器:如果该转换器不能识别此文件,则试用所有的转换器。转换器索引号由 FileConverters 属性返回的转换器行号组成。

AddToMru      Variant 类型,可选。如果该值为 True,则将该工作簿添加到最近使用的文件列表中。默认值为 False。

Local      Variant 类型,可选。如果该值为 True,则以 Microsoft Excel (包括控制面版设置)的语言保存文件。如果该值为 False(默认值),则以 Visual Basic for Applications (VBA) 的语言保存文件,其中 Visual Basic for Applications (VBA) 为典型安装的美国英语版本,除非 VBA 项目的 Workbooks.Open 来自旧的国际化的 XL5/95 VBA 项目。

CorruptLoad      Variant 类型,可选。可为以下常量之一:xlNormalLoad、xlRepairFile 和 xlExtractData。如果未指定任何值,则默认值通常为普通状态,但如果 Excel 已尝试打开该文件,则可以是安全加载或数据恢复状态。首选值为普通状态。如果 Excel 在打开文件时停止操作,则为安全加载状态。如果 Excel 再次停止操作,则为数据恢复状态。

示例

本示例打开 Analysis.xls 工作簿,然后运行 Auto_Open 宏。

Workbooks.Open "ANALYSIS.XLS"


看起来Open方法的参数很多,其实经常用的不多,除了必须的FileName外,最常用的就是Password,用来打开包含有打开权限密码的Excel文件,下面的例子就是打开密码为“123”的ANALYSIS.XLS文件:

Workbooks.Open "ANALYSIS.XLS", Password:="123"


  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
private void Save2Excel() { //string file = "F:\\11\\ck.xlsx"; //string path = "F:\\11\\excel\\"; string time = DateTime.Now.ToString("yyyyMMdd"); string file = System.Windows.Forms.Application.StartupPath + "\\ck.xlsx"; string path = System.Windows.Forms.Application.StartupPath + "\\excel\\"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string saveName1 = path + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"; excel = new CCExcel(file,saveName1); excel.Exceldata(); } private void textBox1_TextChanged(object sender, EventArgs e) { Form1.name = textBox1.Text.ToString(); } private void Form1_Load(object sender, EventArgs e) { comboBox1.Text = 11.ToString(); comboBox2.Text = 100.ToString(); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { Form1.comB1 = comboBox1.Text.ToString(); } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { Form1.comB2 = comboBox2.Text.ToString(); } } public class CCExcel { public Excel.Application appExcel; public Excel.Workbooks wbs; public Excel.Workbook wb; public Excel.Worksheets wss; public Excel.Worksheet ws; private string fileName; private string saveName; public CCExcel(string fileName,string saveName) { // //TODO: 在此处添加构造函数逻辑 // this.fileName = fileName; this.saveName = saveName; } public void Exceldata() { Create(); //Open(fileName); Data2Excel(); Save(saveName); //Save(wb,saveName); //appExcel.ActiveWorkbook.SaveCopyAs(fileName); //判断当前激活的表,并保存这个表。否则,保存时会弹出“是否保存Sheet1.xlsx”的对话框 wb.Close(Type.Missing, Type.Missing, Type.Missing); wbs.Close(); appExcel.Quit(); wb = null; wbs = null; appExcel = null; GC.Collect(); } private void Create()//创建一个Excel对象 { appExcel = new Excel.Application(); wbs = appExcel.Workbooks; wb = wbs.Add(true); //ws = (Excel.Worksheet)wb.ActiveSheet;//这是一个只读sheets集合 //Excel.Worksheet worksheet = wb.ActiveSheet as Excel.Worksheet;//这也是一个只读sheets集合 //Excel.Worksheet ws = (Worksheet)wb.Worksheets[1];//创建工作页sheet单页 ws = wb.Worksheets[1] as Worksheet; //第一个sheet页 ws.Name = "ck"; //这里修改sheet名称 } public void Open(string fileName) { appExcel = new Excel.Application(); wbs = appExcel.Workbooks; wb = wbs.Add(fileName); wb = wbs.Open(fileName,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing); }
Table of Contents | Index Programming Excel with VBA and .NET Preface Part I: Learning VBA Chapter 1. Becoming an Excel Programmer Section 1.1. Why Program? Section 1.2. Record and Read Code Section 1.3. Change Recorded Code Section 1.4. Fix Misteakes Section 1.5. Start and Stop Section 1.6. View Results Section 1.7. Where's My Code? Section 1.8. Macros and Security Section 1.9. Write Bug-Free Code Section 1.10. Navigate Samples and Help Section 1.11. What You've Learned Chapter 2. Knowing the Basics Section 2.1. Parts of a Program Section 2.2. Classes and Modules Section 2.3. Procedures Section 2.4. Variables Section 2.5. Conditional Statements Section 2.6. Loops Section 2.7. Expressions Section 2.8. Exceptions Section 2.9. What You've Learned Chapter 3. Tasks in Visual Basic Section 3.1. Types of Tasks Section 3.2. Interact with Users Section 3.3. Do Math Section 3.4. Work with Text Section 3.5. Get Dates and Times Section 3.6. Read and Write Files Section 3.7. Check Results Section 3.8. Find Truth Section 3.9. Compare Bits Section 3.10. Run Other Applications Section 3.11. Control the Compiler Section 3.12. Not Covered Here Section 3.13. What You've Learned Chapter 4. Using Excel Objects Section 4.1. Objects and Their Members Section 4.2. Get Excel Objects Section 4.3. Get Objects from Collections Section 4.4. About Me and the Active Object Section 4.5. Find the Right Object Section 4.6. Common Members Section 4.7. Respond to Events in Excel Section 4.8. The Global Object Section 4.9. The WorksheetFunction Object Section 4.10. What You've Learned Chapter 5. Creating Your Own Objects Section 5.1. Modules Versus Classes Section 5.2. Add Methods Section 5.3. Create Properties Section 5.4. Define Enumerations Section 5.5. Raise Events Section 5.6. Collect Objects Section 5.7. Expose Objects Section 5.8. Destroy Objects Section 5.9. Things You Can't Do Section 5.10. What You've Learned Chapter 6. Writing Code for Use by Others Section 6.1. Types of Applications Section 6.2. The Development Process Section 6.3. Determine Requirements Section 6.4. Design Section 6.5. Implement and Test Section 6.6. Integrate Section 6.7. Test Platforms Section 6.8. Document Section 6.9. Deploy Section 6.10. What You've Learned Section 6.11. Resources Part II: Excel Objects Chapter 7. Controlling Excel Section 7.1. Perform Tasks Section 7.2. Control Excel Options Section 7.3. Get References Section 7.4. Application Members Section 7.5. AutoCorrect Members Section 7.6. AutoRecover Members Section 7.7. ErrorChecking Members Section 7.8. SpellingOptions Members Section 7.9. Window and Windows Members Section 7.10. Pane and Panes Members Chapter 8. Opening, Saving, and Sharing Workbooks Section 8.1. Add, Open, Save, and Close Section 8.2. Share Workbooks Section 8.3. Program with Shared Workbooks Section 8.4. Program with Shared Workspaces Section 8.5. Respond to Actions Section 8.6. Workbook and Workbooks Members Section 8.7. RecentFile and RecentFiles Members Chapter 9. Working with Worksheets and Ranges Section 9.1. Work with Worksheet Objects Section 9.2. Worksheets and Worksheet Members Section 9.3. Sheets Members Section 9.4. Work with Outlines Section 9.5. Outline Members Section 9.6. Work with Ranges Section 9.7. Range Members Section 9.8. Work with Scenario Objects Section 9.9. Scenario and Scenarios Members Section 9.10. Resources Chapter 10. Linking and Embedding Section 10.1. Add Comments Section 10.2. Use Hyperlinks Section 10.3. Link and Embed Objects Section 10.4. Speak Section 10.5. Comment and Comments Members Section 10.6. Hyperlink and Hyperlinks Members Section 10.7. OleObject and OleObjects Members Section 10.8. OLEFormat Members Section 10.9. Speech Members Section 10.10. UsedObjects Members Chapter 11. Printing and Publishing Section 11.1. Print and Preview Section 11.2. Control Paging Section 11.3. Change Printer Settings Section 11.4. Filter Ranges Section 11.5. Save and Display Views Section 11.6. Publish to the Web Section 11.7. AutoFilter Members Section 11.8. Filter and Filters Members Section 11.9. CustomView and CustomViews Members Section 11.10. HPageBreak, HPageBreaks, VPageBreak, VPageBreaks Members Section 11.11. PageSetup Members Section 11.12. Graphic Members Section 11.13. PublishObject and PublishObjects Members Section 11.14. WebOptions and DefaultWebOptions Members Chapter 12. Loading and Manipulating Data Section 12.1. Working with QueryTable Objects Section 12.2. QueryTable and QueryTables Members Section 12.3. Working with Parameter Objects Section 12.4. Parameter Members Section 12.5. Working with ADO and DAO Section 12.6. ADO Objects and Members Section 12.7. DAO Objects and Members Section 12.8. DAO.Database and DAO.Databases Members Section 12.9. DAO.Document and DAO.Documents Members Section 12.10. DAO.QueryDef and DAO.QueryDefs Members Section 12.11. DAO.Recordset and DAO.Recordsets Members Chapter 13. Analyzing Data with Pivot Tables Section 13.1. Quick Guide to Pivot Tables Section 13.2. Program Pivot Tables Section 13.3. PivotTable and PivotTables Members Section 13.4. PivotCache and PivotCaches Members Section 13.5. PivotField and PivotFields Members Section 13.6. CalculatedFields Members Section 13.7. CalculatedItems Members Section 13.8. PivotCell Members Section 13.9. PivotFormula and PivotFormulas Members Section 13.10. PivotItem and PivotItems Members Section 13.11. PivotItemList Members Section 13.12. PivotLayout Members Section 13.13. CubeField and CubeFields Members Section 13.14. CalculatedMember and CalculatedMembers Members Chapter 14. Sharing Data Using Lists Section 14.1. Use Lists Section 14.2. ListObject and ListObjects Members Section 14.3. ListRow and ListRows Members Section 14.4. ListColumn and ListColumns Members Section 14.5. ListDataFormat Members Section 14.6. Use the Lists Web Service Section 14.7. Lists Web Service Members Section 14.8. Resources Chapter 15. Working with XML Section 15.1. Understand XML Section 15.2. Save Workbooks as XML Section 15.3. Use XML Maps Section 15.4. Program with XML Maps Section 15.5. XmlMap and XmlMaps Members Section 15.6. XmlDataBinding Members Section 15.7. XmlNamespace and XmlNamespaces Members Section 15.8. XmlSchema and XmlSchemas Members Section 15.9. Get an XML Map from a List or Range Section 15.10. XPath Members Section 15.11. Resources Chapter 16. Charting Section 16.1. Navigate Chart Objects Section 16.2. Create Charts Quickly Section 16.3. Embed Charts Section 16.4. Create More Complex Charts Section 16.5. Choose Chart Type Section 16.6. Create Combo Charts Section 16.7. Add Titles and Labels Section 16.8. Plot a Series Section 16.9. Respond to Chart Events Section 16.10. Chart and Charts Members Section 16.11. ChartObject and ChartObjects Members Section 16.12. ChartGroup and ChartGroups Members Section 16.13. SeriesLines Members Section 16.14. Axes and Axis Members Section 16.15. DataTable Members Section 16.16. Series and SeriesCollection Members Section 16.17. Point and Points Members Chapter 17. Formatting Charts Section 17.1. Format Titles and Labels Section 17.2. Change Backgrounds and Fonts Section 17.3. Add Trendlines Section 17.4. Add Series Lines and Bars Section 17.5. ChartTitle, AxisTitle, and DisplayUnitLabel Members Section 17.6. DataLabel and DataLabels Members Section 17.7. LeaderLines Members Section 17.8. ChartArea Members Section 17.9. ChartFillFormat Members Section 17.10. ChartColorFormat Members Section 17.11. DropLines and HiLoLines Members Section 17.12. DownBars and UpBars Members Section 17.13. ErrorBars Members Section 17.14. Legend Members Section 17.15. LegendEntry and LegendEntries Members Section 17.16. LegendKey Members Section 17.17. Gridlines Members Section 17.18. TickLabels Members Section 17.19. Trendline and Trendlines Members Section 17.20. PlotArea Members Section 17.21. Floor Members Section 17.22. Walls Members Section 17.23. Corners Members Chapter 18. Drawing Graphics Section 18.1. Draw in Excel Section 18.2. Create Diagrams Section 18.3. Program with Drawing Objects Section 18.4. Program Diagrams Section 18.5. Shape, ShapeRange, and Shapes Members Section 18.6. Adjustments Members Section 18.7. CalloutFormat Members Section 18.8. ColorFormat Members Section 18.9. ConnectorFormat Members Section 18.10. ControlFormat Members Section 18.11. FillFormat Members Section 18.12. FreeFormBuilder Section 18.13. GroupShapes Members Section 18.14. LineFormat Members Section 18.15. LinkFormat Members Section 18.16. PictureFormat Members Section 18.17. ShadowFormat Section 18.18. ShapeNode and ShapeNodes Members Section 18.19. TextFrame Section 18.20. TextEffectFormat Section 18.21. ThreeDFormat Chapter 19. Adding Menus and Toolbars Section 19.1. About Excel Menus Section 19.2. Build a Top-Level Menu Section 19.3. Create a Menu in Code Section 19.4. Build Context Menus Section 19.5. Build a Toolbar Section 19.6. Create Toolbars in Code Section 19.7. CommandBar and CommandBars Members Section 19.8. CommandBarControl and CommandBarControls Members Section 19.9. CommandBarButton Members Section 19.10. CommandBarComboBox Members Section 19.11. CommandBarPopup Members Chapter 20. Building Dialog Boxes Section 20.1. Types of Dialogs Section 20.2. Create Data-Entry Forms Section 20.3. Design Your Own Forms Section 20.4. Use Controls on Worksheets Section 20.5. UserForm and Frame Members Section 20.6. Control and Controls Members Section 20.7. Font Members Section 20.8. CheckBox, OptionButton, ToggleButton Members Section 20.9. ComboBox Members Section 20.10. CommandButton Members Section 20.11. Image Members Section 20.12. Label Members Section 20.13. ListBox Members Section 20.14. MultiPage Members Section 20.15. Page Members Section 20.16. ScrollBar and SpinButton Members Section 20.17. TabStrip Members Section 20.18. TextBox and RefEdit Members Chapter 21. Sending and Receiving Workbooks Section 21.1. Send Mail Section 21.2. Work with Mail Items Section 21.3. Collect Review Comments Section 21.4. Route Workbooks Section 21.5. Read Mail Section 21.6. MsoEnvelope Members Section 21.7. MailItem Members Section 21.8. RoutingSlip Members Part III: Extending Excel Chapter 22. Building Add-ins Section 22.1. Types of Add-ins Section 22.2. Code-Only Add-ins Section 22.3. Visual Add-ins Section 22.4. Set Add-in Properties Section 22.5. Sign the Add-in Section 22.6. Distribute the Add-in Section 22.7. Work with Add-ins in Code Section 22.8. AddIn and AddIns Members Chapter 23. Integrating DLLs and COM Section 23.1. Use DLLs Section 23.2. Use COM Applications Chapter 24. Getting Data from the Web Section 24.1. Perform Web Queries Section 24.2. QueryTable and QueryTables Web Query Members Section 24.3. Use Web Services Section 24.4. Resources Chapter 25. Programming Excel with .NET Section 25.1. Approaches to Working with .NET Section 25.2. Create .NET Components for Excel Section 25.3. Use .NET Components in Excel Section 25.4. Use Excel as a Component in .NET Section 25.5. Create Excel Applications in .NET Section 25.6. Resources Chapter 26. Exploring Security in Depth Section 26.1. Security Layers Section 26.2. Understand Windows Security Section 26.3. Password-Protect and Encrypt Workbooks Section 26.4. Program with Passwords and Encryption Section 26.5. Workbook Password and Encryption Members Section 26.6. Excel Password Security Section 26.7. Protect Items in a Workbook Section 26.8. Program with Protection Section 26.9. Workbook Protection Members Section 26.10. Worksheet Protection Members Section 26.11. Chart Protection Members Section 26.12. Protection Members Section 26.13. AllowEditRange and AllowEditRanges Members Section 26.14. UserAccess and UserAccessList Members Section 26.15. Set Workbook Permissions Section 26.16. Program with Permissions Section 26.17. Permission and UserPermission Members Section 26.18. Add Digital Signatures Section 26.19. Set Macro Security Section 26.20. Set ActiveX Control Security Section 26.21. Distribute Security Settings Section 26.22. Using the Anti-Virus API Section 26.23. Common Tasks Section 26.24. Resources Part IV: Appendixes Appendix A. Reference Tables Section A.1. Dialogs Collection Constants Section A.2. Common Programmatic IDs Appendix B. Version Compatibility Section B.1. Summary of Version Changes Section B.2. Macintosh Compatibility About the Author Colophon Index
请帮我优化以下代码,使他在对比时如果只有原数据一行的情况就按代码的逻辑复制这一行并粘贴Sub CopySameDay() Dim ws As Worksheet Dim lastRow As Long Dim i As Long Dim copyRange As Range Dim pasteRange As Range Dim wb As Workbook Dim folderPath As String Dim fileName As String Dim asteRange As Range Set ws = ActiveSheet lastRow = ws.Cells(Rows.Count, "D").End(xlUp).Row For i = 2 To lastRow If Format(ws.Range("D" & i).Value, "yyyy-mm-dd") = Format(ws.Range("D" & i - 1).Value, "yyyy-mm-dd") And ws.Range("B" & i).Value = ws.Range("B" & i - 1).Value Then If copyRange Is Nothing Then Set copyRange = ws.Range("A" & i - 1) End If Set pasteRange = ws.Range("A" & i) Else If Not copyRange Is Nothing Then folderPath = Left(ThisWorkbook.FullName, InStrRev(ThisWorkbook.FullName, "\")) Set asteRange = ws.Range("B" & i - 1) fileName = asteRange.Value & ".xlsx" If Dir(folderPath & fileName) = "" Then Set wb = Workbooks.Add wb.SaveAs folderPath & fileName Else Set wb = Workbooks.Open(folderPath & fileName) End If wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count)).Name = Format(copyRange.Offset(0, 3).Value, "yyyy-mm-dd") copyRange.Resize(i - copyRange.Row, ws.Columns.Count).Copy wb.Sheets(wb.Sheets.Count).Range("A1").PasteSpecial xlPasteValues wb.Save wb.Close Set copyRange = Nothing End If End If Next i If Not copyRange Is Nothing Then folderPath = Left(ThisWorkbook.FullName, InStrRev(ThisWorkbook.FullName, "\")) Set asteRange = ws.Range("B" & i - 1) fileName = asteRange.Value & ".xlsx" If Dir(folderPath & fileName) = "" Then Set wb = Workbooks.Add wb.SaveAs folderPath & fileName Else Set wb = Workbooks.Open(folderPath & fileName) End If wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count)).Name = Format(copyRange.Offset(0, 3).Value, "yyyy-mm-dd") copyRange.Resize(lastRow - copyRange.Row + 1, ws.Columns.Count).Copy wb.Sheets(wb.Sheets.Count).Range("A1").PasteSpecial xlPasteValues wb.Save wb.Close End If End Sub
05-28
Sub CopySameDay() Dim ws As Worksheet Dim lastRow As Long Dim i As Long Dim copyRange As Range Dim pasteRange As Range Dim wb As Workbook Dim folderPath As String Dim fileName As String Dim asteRange As Range Set ws = ActiveSheet lastRow = ws.Cells(Rows.Count, "D").End(xlUp).Row For i = 2 To lastRow If Format(ws.Range("D" & i).Value, "yyyy-mm-dd") = Format(ws.Range("D" & i - 1).Value, "yyyy-mm-dd") And ws.Range("B" & i).Value = ws.Range("B" & i - 1).Value Then If copyRange Is Nothing Then Set copyRange = ws.Range("A" & i - 1) End If Set pasteRange = ws.Range("A" & i) Else If Not copyRange Is Nothing Then folderPath = Left(ThisWorkbook.FullName, InStrRev(ThisWorkbook.FullName, "\")) Set asteRange = ws.Range("B" & i - 1) fileName = asteRange.Value & ".xlsx" If Dir(folderPath & fileName) = "" Then Set wb = Workbooks.Add wb.SaveAs folderPath & fileName Else Set wb = Workbooks.Open(folderPath & fileName) End If wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count)).Name = Format(copyRange.Offset(0, 3).Value, "yyyy-mm-dd") copyRange.Resize(i - copyRange.Row, ws.Columns.Count).Copy wb.Sheets(wb.Sheets.Count).Range("A1").PasteSpecial xlPasteValues wb.Save wb.Close Set copyRange = Nothing End If End If Next i If Not copyRange Is Nothing Then folderPath = Left(ThisWorkbook.FullName, InStrRev(ThisWorkbook.FullName, "\")) Set asteRange = ws.Range("B" & i - 1) fileName = asteRange.Value & ".xlsx" If Dir(folderPath & fileName) = "" Then Set wb = Workbooks.Add wb.SaveAs folderPath & fileName Else Set wb = Workbooks.Open(folderPath & fileName) End If wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count)).Name = Format(copyRange.Offset(0, 3).Value, "yyyy-mm-dd") copyRange.Resize(lastRow - copyRange.Row + 1, ws.Columns.Count).Copy wb.Sheets(wb.Sheets.Count).Range("A1").PasteSpecial xlPasteValues wb.Save wb.Close End If End Sub 优化后的代码只在最后一行数据为唯一数据时进行额外的复制操作。在原代码中,在最后一行数据为唯一数据时,会进行两次复制操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值