下一个循环语法

问题描述 投票:0回答:1
Sub test()
' I have two spreadsheets: Managers and Reports
' Managers is a list of managers
' Report has all the managers and all the people that report to them
' I want to use the Managers spreadsheet as a source to filter the report spreadsheet for all the people that report to that manager
' and them copy the filtered data to a tab in the reports spreadsheet.
' There is a tab in the reports spreadsheet that is named after the manager
' So John Doe is on the list of managers on the manager sheet
' I want to filter the report spreadsheet for John Doe and then copy the filtered data to a tab on the reports spreadsheet named John Doe
' The reports spreadsheet already has a tab named John Doe

' so i think i need to define both spreadsheets
Dim wbSource As Workbook
Dim wbReport As Workbook

'and define the tabs in each workbook
Dim wsManagers As Worksheet
Dim wsReport As Worksheet

'and define the range in the source spreadsheet that has the names
Dim n As Range
' n = wbSource wsManagers ' I don't know the syntax here

'  So I'm thinking I need a for next loop to go through the list of managers
' filter the report spreadsheet
' copy that filtered data to the appropriate tab in the report spreadsheet

n = 1
For n = 1 To 127
    'Filter report spreadsheet
    ' copy filtered data to correct tab
Next n

End Sub

这是很多,我花了几个小时试图让一些东西发挥作用 任何帮助将不胜感激。

excel vba loops
1个回答
0
投票

此代码是该任务的最小方法。仅使用一本工作簿,其中工作表名为

Managers
Report
。在开始代码之前,请检查是否存在以经理姓名命名的工作表。

Sub filter_managers()

Dim wsManagers As Worksheet, wsReport As Worksheet
Set wsManagers = Worksheets("Managers")
Set wsReport = Worksheets("Report")

With wsManagers
  Set manager_range = .Range(.Range("A1"), .Range("A1").End(xlDown))
End With
For i = 1 To manager_range.Rows.Count
  Set man_sheet = Worksheets.Add(, Worksheets(Worksheets.Count))
  man_name = wsManagers.Cells(i, 1)
  wsReport.UsedRange.AutoFilter 1, man_name
  wsReport.Cells.SpecialCells(xlCellTypeVisible).Copy man_sheet.Range("A1")
  man_sheet.Name = man_name
  wsReport.ShowAllData
Next i
wsReport.Range("A1").AutoFilter
End Sub

© www.soinside.com 2019 - 2024. All rights reserved.