简体   繁体   English

Excel VBA循环直到空白单元格并将工作表复制到新工作簿

[英]Excel VBA loop until blank cell and copy worksheet to new workbook

I have a list of ID#s in column A on Sheet 2 (starting at cell A2). 我在工作表2的A列中有一个ID#列表(从单元格A2开始)。

I am trying to create a macro to loops through each ID #, copies it into cell A9 on Sheet 1 and then copies Sheet 3 into a new workbook. 我正在尝试创建一个宏来遍历每个ID#,将其复制到工作表1的单元格A9中,然后将工作表3复制到新的工作簿中。

For each ID#, Sheet 3 should be copied into that same new workbook under a different worksheet/tab. 对于每个ID#,应将工作表3复制到相同的新工作簿中的不同工作表/选项卡下。

I am not a coder so all I have is what I can find on Google and I can't seem to get everything in order. 我不是编码人员,所以我所拥有的只是我可以在Google上找到的东西,而且似乎无法使所有事情井井有条。 Any and all help is greatly appreciated. 任何帮助都将不胜感激。

This is what I have so far.. what i cant figure out is how to end the loop at blank cell, how to get the macro to revert back to the source after copying worksheet to new workbook, and then how to add the subsequent loops to that now existing workbook. 这是我到目前为止所拥有的..我无法弄清楚的是如何在空白单元格处结束循环,将工作表复制到新工作簿后,如何使宏返回到源,然后如何添加后续循环到现有的工作簿。

    Sub Test1()
  Dim x As Integer
  Application.ScreenUpdating = False
  ' Set numrows = number of rows of data.
  NumRows = Range("a2", Range("a2").End(xlDown)).Rows.Count
  ' Select cell a2.
  Range("a2").Select
  ' Establish "For" loop to loop "numrows" number of times.
  For x = 1 To NumRows
     Sheets("Sheet 1").Range("A9").Value = ActiveCell
      Sheets("Sheet 3").Copy
     ' Selects cell down 1 row from active cell.
     ActiveCell.Offset(1, 0).Select
  Next
  Application.ScreenUpdating = True

End Sub 结束子

There isn't much of your code left apart from ScreenUpdating, For and Next. 除了ScreenUpdating,For和Next,您的代码很少。 I've commented some steps where it may not be obvious why they are being done. 我已评论了一些步骤,这些步骤可能并不十分清楚为什么要执行这些步骤。 There's some additional comments about things you may not be familiar with. 关于您可能不熟悉的事情,还有一些其他评论。

Sub CopySheetsToNewWB()
Dim ID_cell As Range 'will be used to control loop flow
Dim SourceWB As Workbook
Dim DestWB As Workbook
Dim ControlSheet As Worksheet 'sheet with ID#s
Dim IDsToCopy As Range
Dim SheetToCopy As Worksheet
Dim PathSeparator As String
Dim SaveName As String

    Application.ScreenUpdating = False
    Set SourceWB = ThisWorkbook
    'test if file saved on device/network or cloud and set separator
    'because new file will be saved in same location
    If InStr(1, SourceWB.Path, "\") > 0 Then
        PathSeparator = "\"
    Else
        PathSeparator = "/"
    End If
    Set ControlSheet = SourceWB.Sheets("Sheet2")
    Set SheetToCopy = SourceWB.Sheets("Sheet3")
    With ControlSheet
        Set IDsToCopy = Range(.[A2], .[A2].End(xlDown))
    End With
    For Each ID_cell In IDsToCopy
        'As ID_Cell is based on an IFERROR(...,"") formula, test if blank.
        If ID_cell <> "" Then
            With SourceWB 'allows subsequent commands without having to specify it
                .Sheets("Sheet1").[A9] = ID_cell.Value2
                'Test if DestWB already exists
                If Not DestWB Is Nothing Then
                    'it's not nothing so it must be something (i.e. it exists)
                    SheetToCopy.Copy after:=DestWB.Sheets(DestWB.Sheets.Count)
                Else
                    'create DestWB and save it in the same location as SourceWB
                    'using SourceWB name with date appended and SourceWB file extension.
                    'INSTR is similar to FIND in Excel but doesn't error if search
                    'string is not found - just returns 0.  INSTRREV finds position of
                    'the last instance of searched string (in case of "."s in filename).
                    SaveName = .Path & PathSeparator & Left(.Name, InStr(1, .Name, ".") - 1) _
                    & " as at " & _
                    Format(Date, "yyyymmdd") & _
                    Right(.Name, Len(.Name) - InStrRev(.Name, ".") + 1)
                    SheetToCopy.Copy
                    ActiveWorkbook.SaveAs Filename:=SaveName, FileFormat:=SourceWB.FileFormat
                    Set DestWB = ActiveWorkbook
                End If
            End With
            'Copied sheet may have formulas linking to SourceWB so change to values
            'and as it's still named "Sheet3", rename it after ID#
            With DestWB.Sheets("Sheet3")
                .UsedRange.Copy
                .[A1].PasteSpecial xlPasteValues
                .Name = ID_cell.Value2
            End With
        End If
    Next
    DestWB.Save
  Application.ScreenUpdating = True
End Sub

All variables are declared - you can and should set your VBA editor to "Require Variable Declaration" (under Tools -> Options). 所有变量都已声明-您可以并且应该将VBA编辑器设置为“需要变量声明”(在“工具”->“选项”下)。 This will insert "Option Explicit" at the top of every new module. 这将在每个新模块的顶部插入“ Option Explicit”。

There are no "Select" or "Activate" commands. 没有“选择”或“激活”命令。 You can usually avoid them by using With...EndWith structures or fully qualifying objects. 通常可以通过使用With ... EndWith结构或完全合格的对象来避免它们。

Square bracket range references - [A2] is the same as Range("A2"). 方括号范围参考-[A2]与Range(“ A2”)相同。

Any questions, post a comment. 如有任何疑问,请发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM