简体   繁体   English

将3个工作表复制到新工作簿-1个仅具有可见单元格-其他2个仅具有值

[英]Copy 3 worksheets to new workbook - 1 with visible cells only - the other 2 with values only

I'm new here and to vba in general. 我是新来的,而且对vba来说还是新的。 I basically just read myself into the matter for my new job. 我基本上只是为自己的新工作读了自己的书。 So please bear with me. 所以,请忍受我。 I'm looking for a solution to my issue and found seperate solutions for parts but I'm not able to piece them together. 我正在寻找解决方案,找到了零件的单独解决方案,但无法将它们组合在一起。

My goal is the following: Copy 3 Worksheets of a workbook to a new one (not existing yet) and save it under the current date with a specific name. 我的目标是:将工作簿的3个工作表复制到一个新的工作簿(尚不存在),并在当前日期下以特定名称保存。 Here's the code that I put together so far for that which works fine. 到目前为止,这是我整理好的代码。

Sub export()

Dim path As String
Dim file As String
Dim ws As Worksheet
Dim rng As Range

path = "D:\@Inbox\"
file = Format(Date, "YYYY-MM-DD") & " " & Format(Time, "hhmm") & " " &     "accr " & Format(DateSerial(Year(Date), Month(Date), 1), "YYYY_MM") & " city" & ".xlsx"

Application.ScreenUpdating = False

Sheets(Array("Accr", "Pivot", "Segments")).Select
Sheets(Array("Accr", "Pivot", "Segments")).Copy
ActiveSheet.UsedRange.Value = ActiveSheet.UsedRange.Value

For Each ws In Worksheets
ws.Rectangles.Delete
Next
Sheets(Array("Pivot", "Segments")).Visible = False

ActiveWorkbook.SaveAs Filename:=path & file, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close

Sheets("Menu =>").Select
Range("C1").Select

End Sub

1st condition: the new workbook should not be created manually and opened first, but the macro should do that. 第一个条件:不应手动创建新工作簿并先打开它,但是宏应该这样做。

2nd condition: the 1st workbook should have autofilters selected and then only visible cells copied. 第二个条件:第一个工作簿应选择自动过滤器,然后仅复制可见的单元格。 Is that possible as a whole worksheet, or do I have to copy the cells and create a worksheet in the new workbook? 是否有可能作为一个整体工作表,还是我必须复制单元格并在新工作簿中创建一个工作表? Here's the code for the filter 这是过滤器的代码

Sheets("Accr").Select
Reset_Filter
Selection.AutoFilter Field:=1, Criteria1:="12"
Selection.AutoFilter Field:=2, Criteria1:="booked"
Selection.AutoFilter Field:=35, Criteria1:="Frankfurt"
Set rng = Application.Intersect(ActiveSheet.UsedRange)
rng.SpecialCells(xlCellTypeVisible).Copy

3rd condition: the other two worksheets should be copied without formulas but with format. 第三个条件:应复制其他两个工作表,而不使用公式,但使用格式。 (That is included in the first code sample) (这包含在第一个代码示例中)

My problem is now, to piece everything together so that there are 3 worksheets in the new workbook containing in the first ws the visible cells of the source ws with the autofilter and the other two worksheets containing only the data and the format and being hidden. 我的问题是,将所有内容组合在一起,以便新工作簿中有3个工作表,其中第一个ws包含带有自动筛选器的源ws的可见单元格,而另外两个工作表仅包含数据和格式并被隐藏。 Info to my reasoning: the first worksheet refers with the formulas to the other two worksheets so that the recipients of the file have preselected fields and lists to fill out the cells. 我的推理信息:第一个工作表使用公式引用其他两个工作表,以便文件的收件人具有预先选择的字段和列表以填写单元格。

Thank you very much in advance. 提前非常感谢您。

EDIT: Background Info: The Accr sheet contains accrual informattion and has the Month information in column A. Since several years should be also able to be compared in one Pivot Table later on, the format was changed from a mere number to a date (format: MM.YYYY ). 编辑:背景信息: Accr工作表包含应计信息,并且在A列中有Month信息。由于以后还可以在一个数据透视表中比较几年,因此该格式从单纯的数字更改为日期(格式: MM.YYYY )。

Edit 编辑

Alright, here is a different code, this copies the worksheets then removes the rows in Accr which do not meet the criteria. 好的,这是一个不同的代码, Accr复制工作表,然后删除Accr中不符合条件的行。 Be sure to make ranges absolute, put $ in front of the column and row in a formula, the vlookup you mentioned should become =VLOOKUP(R2097;Segments!$G:$Q;11;0) and this goes for any formula on the Accr sheet that references a fixed range anywhere. 请务必范围绝对的,把$列的前面,排在公式中,该vlookup你提到的应该成为=VLOOKUP(R2097;Segments!$G:$Q;11;0)这也同样适用于式上在任何地方引用固定范围的Accr表。

 Sub Export() Dim NewWorkbook As Workbook Dim Ws As Worksheet Dim fPath As String, fName As String Dim i As Long Dim RowsToDelete As Range Application.ScreenUpdating = False Application.DisplayAlerts = False Set NewWorkbook = Workbooks.Add fPath = "D:\\@Inbox\\" fName = VBA.Format(VBA.Date, "YYYY-MM-DD") & " " & VBA.Format(VBA.Time, "hhmm") & " " & "accr " & VBA.Format(VBA.DateSerial(VBA.Year(VBA.Date), VBA.Month(VBA.Date), 1), "YYYY_MM") & " city" NewWorkbook.SaveAs fPath & fName, xlOpenXMLWorkbook ThisWorkbook.Worksheets(Array("Accr", "Pivot", "Segments")).Copy NewWorkbook.Worksheets(1) For Each Ws In NewWorkbook.Worksheets With Ws If Not .Name = "Accr" And Not .Name = "Pivot" And Not .Name = "Segments" Then .Delete ElseIf Ws.Name = "Accr" Then For i = 4 To .Cells(.Rows.Count, 1).End(xlUp).Row If Not .Cells(i, 1) = .Cells(i, 1) = Month(ThisWorkbook.Worksheets("Mon").Cells(19, 2)) And Not .Cells(i, 2) = "booked" And Not .Cells(i, 35) = "Frankfurt" Then If RowsToDelete Is Nothing Then Set RowsToDelete = .Rows(i).EntireRow Else Set RowsToDelete = Union(RowsToDelete, .Rows(i).EntireRow) End If End If Next i If Not RowsToDelete Is Nothing Then RowsToDelete.Delete xlUp End If ElseIf .Name = "Pivot" Or .Name = "Segments" Then .Visible = xlSheetHidden .UsedRange = Ws.UsedRange.Value End If End With Next Ws NewWorkbook.Save NewWorkbook.Close Application.Goto ThisWorkbook.Worksheets("Menu =>").Cells(1, 3) Application.ScreenUpdating = True Application.DisplayAlerts = True End Sub 

End of edit 编辑结束

Ok... so after fiddling around with it a while and collecting several pieces of information around this website, I finally have a solution. 好吧...所以在摆弄了一段时间并在此网站上收集了几条信息之后,我终于有了解决方案。

The main problem, was the first criteria, which is a date field. 主要问题是第一个条件,即日期字段。 I found out that vba has its problems when the date is not in US-Format. 我发现,当日期不是美式格式时,vba会出现问题。 So I made a workaround and made a textformat date in my parameter worksheet, so that I always have the export of the sheets for the current month set in the workbook. 因此,我做了一个变通办法,并在参数工作表中指定了文本格式的日期,以便始终在工作簿中设置当前月份的工作表导出。 In my accruals-data I just had to change the format in column A to have text (eg '01.2016). 在我的应计数据中,我只需要更改A列中的格式即可使用文本(例如'01 .2016)。 Plus I optimized my rawdata a little bit, so that I only have to export one additional worksheet, which will be hidden and contains only hardcopy values, so that there is no external link to my original file anymore. 另外,我对原始数据进行了一些优化,因此我只需要导出一个其他工作表,该工作表将被隐藏并且仅包含硬拷贝值,因此不再有指向我的原始文件的外部链接。

Sub ACTION_Export_AbgrBerlin()
Dim Pfad As String
Dim Dateiname As String
Dim ws As Worksheet
Dim oRow As Range, rng As Range
Dim myrows As Range

' define filepath and filename
Pfad = "D:\@Inbox\"
Dateiname = Format(Date, "YYYY-MM-DD") & " " & Format(Time, "hhmm") & " " & "Abr " _
& Format(DateSerial(Year(Date), Month(Date), 1), "yyyy-mm") & " Berlin" & ".xlsx"


Application.ScreenUpdating = False

Sheets(Array("Abgr", "Masterdata MP")).Copy

' hardcopy of values
Sheets("Masterdata MP").UsedRange = Sheets("Masterdata MP").UsedRange.Value
' delete Macrobuttons and Hyperlinks
    For Each ws In Worksheets
    ws.Rectangles.Delete
    ws.Hyperlinks.Delete
    Next
' delete first 3 rows (that are placeholders for the macrobuttons in the original file)
    With Sheets("Abgr")
    .AutoFilterMode = False
    .Rows("1:3").EntireRow.Delete

' set Autofilter matching the following criteria
    .Range("A1:AO1048576").AutoFilter
'refer to parameter worksheet which contains the current date as textformat
    .Range("A1:AO1048576").AutoFilter Field:=1, Criteria1:=ThisWorkbook.Worksheets("Mon").Range("E21")
    .Range("A1:AO1048576").AutoFilter Field:=2, Criteria1:=Array(1, "gebucht")
    .Range("A1:AO1048576").AutoFilter Field:=36, Criteria1:=Array(1, "Abgr Berlin")
    End With
'delete hidden rows i.e. delete anything but the selection
    With Sheets("Abgr")
    Set myrows = Intersect(.Range("A:A").EntireRow, .UsedRange)
    End With

    For Each oRow In myrows.Columns(1).Cells
        If oRow.EntireRow.Hidden Then
            If rng Is Nothing Then
                Set rng = oRow
            Else
                Set rng = Union(rng, oRow)
            End If
        End If
    Next

    If Not rng Is Nothing Then rng.EntireRow.Delete

    Sheets("Masterdata MP").Visible = xlSheetHidden
    Sheets("Masterdata MP").UsedRange = Sheets("Masterdata MP").UsedRange.Value


    ActiveWorkbook.SaveAs Filename:=Pfad & Dateiname, FileFormat:=xlOpenXMLWorkbook
    ActiveWorkbook.Close
  'go back to main menu in original workbook  
    Sheets("Menu").Select
End Sub

Now I can create one sub for each file I have to create and then run all the subs after each other. 现在,我可以为必须创建的每个文件创建一个子文件,然后依次运行所有子文件。 That saves me a bunch of time. 那节省了我很多时间。 The part with the hidden rows, I found here Delete Hidden/Invisible Rows after Autofilter Excel VBA 具有隐藏行的部分,我在这里找到了自动过滤Excel VBA后删除隐藏/不可见的行

Thanks again @silentrevolution for your help, it gave me the pointers to get the needed result. 再次感谢@silentrevolution的帮助,它为我提供了获得所需结果的指针。

It's not the cleanest code and I'm sure that it can be made a bit leaner, so I would appreciate any recommendations. 这不是最干净的代码,我敢肯定可以使其更精简一些,因此我将不胜感激任何建议。 But for now it serves my needs. 但是现在它满足了我的需求。

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

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