【问题标题】:Copying a specific range from one worksheet to another worksheet将特定范围从一个工作表复制到另一个工作表
【发布时间】:2018-02-17 14:10:57
【问题描述】:

我有一个工作表,我想梳理一下具体的程序名称。当找到该程序名称时,我的代码将从ACV 列中选择正确的行,并继续这样做,直到最后一行具有单元格值。最后,它会复制选定的行并将它们粘贴到创建的新工作簿中。

话虽如此,我的rng 联合(在我的For i 循环中)由于某种原因无法正常工作。它从我正在创建的 new 工作簿中复制值,而不是从工作簿 wbthis 中复制值。我试过使用test.Range(Cells(i,1), Cells(i, 78)),但这也不起作用。选择整行的注释 For 循环有效,但我不想要整行。

Sub ProgramExport()
  'Dim arr

  'arr3 = Array("Accessible Pedestrian Signals", "Advanced Traffic Signal Control ", "Bathurst Street Bridge Rehabilitation ", "C.I. Centennial Pk Path", _
               "C.I. Etobicoke Valley PK", "C.I. Humber Trail Extension and Gaps", "C.I. Pan Am Trail Expansion - Gatineau Trail", _
               "City Bridge Rehabilitation ", "City-10-Surface Transit Operational Improvement Studies - Phase 3", _
               "City-11-King Street Modelling Study", "City-12-REimagining Yonge North Study", "City-15-Flemingdon Park-Thorncliffe Park Neighbourhood  Cycling Connections", _
               "City-22-Accessible Pedestrian Signals Expansion", "City-26-Geometric Safety Improvements - Removal of Channelized Right Turns", _
               "City-27-Missing sidewalk links - 2017", "City-28-Missing sidewalk links - 2018", "City-37-Installation of Cycling Facilites on Woodbine Ave.", _
               "City-38-Installation of Cycling Facilities on Lakeshore Blvd West", "City-39-Surface Transit Operational Improvement Studies - Phase 1", _
               "City-40-King Street Pilot Implementation", "City-42-Yonge Tomorrow", "City-6-Eglinton Connects Streetscape Improvements and Cycle Tracks", _
               "City-8-East Don Trail", "City-9-Surface Transit Operational Improvement Studies - Phase 2", "Critical Interim Road Rehabilitation ", _
               "Cycling Infrastructure ", "Design of Cherry St Realignment and Bridges", "Ditch Rehabilitation and Culvert Reconstruction", _
               "Don Valley Parkway Rehabilitation", "Engineering Studies", "F.G. Gardiner Interim Repairs", "Facility Improvements ", _
               "Georgetown South City Infrastructure Upgrades", "Greenville and Yonge Street Improvements", _
               "Growth Related Capital Works ", "Guide Rail Replacement Program", "John Street Revitalization Project", "King Liberty Cycling Pedestrian Bridge", _
               "Laneways", "LARP (Lawrence-Allen Revitalization Project) Phase 1", "LED signal Module Conversion ", "Legion Road Extension & Grade Separation", _
               "Local Road Rehabilitation", "Local Speed Limit Reduction", "Major Roads Rehabilitation", "Major SOGR Pooled Contingency ", _
               "N.I. Mill Street Streetscape", "N.I. The Queensway from Islington to Royal York", "Neighborhood Improvements", _
               "North York Service Road Extension", "Pedestrian Safety and Infrastructure Program", _
               "Port Union Road ( Lawrence Ave - Kingston Rd)", "PSI Homewood Depressed Curb", "PXO Visibility Enhancement", _
               "Regent Park Revitalization ", "Retaining Walls Rehabilitation ", "Road Safety Plan (LGTSI) ", "Rouge National Park ", _
               "Salt Management Program", "Sidewalks", "Signs and Markings Asset Management", "Six Points Interchange Redevelopment", _
               "SM Bay Cloverdale", "SM McGill-Granby Village", "SM The Upper Avenue", "Steeles Widenings ( Tapscott Road - Beare Road) ", _
               "System Enhancements for Road Repair & Permits", "Tactile Domes Installation", "Third Party Signals ", "Traffic - Control RESCU", _
               "Traffic Calming", "Traffic Congestion Management ", _
               "Traffic Signals Major Modifications", "Transportation Safety & Local Improvement Program ", "Work for TTC & Others", _
               "Yonge Street Revitalization EA Study (Reimagining Yonge)")

  Dim Program As Range
  Dim rng As Range
  Dim wbThis As Workbook
  Dim newBook As Workbook
  Dim value As String
  Dim userID As String
  Dim fn As String
  Dim programN As Variant
  Dim Cell As Range
  Dim sName As String
  userID = InputBox("Please enter your user id.")

  'For Each programN In arr3
      programN = "Local Road Rehabilitation"
      Set Program = Range("C1:C2000")
      Set newBook = Workbooks.Add
      'UserForm1.Show
      Set wbThis = Workbooks("TS L2L3v111.xlsm")
      Dim test As Worksheet: Set test = wbThis.Worksheets(4)
      'value = InputBox("Please enter the program you'd like to export.")
      fn = "C:\Users\" & userID & "\Desktop\" & programN & ".xlsx"
      'aFN = "C:\Users\ashaikh5\Desktop\Copy of TS L2L3v11.xlsm"
      newBook.SaveAs (fn)
      'FileFormat:=52

      For i = 1 To 2000
         If test.Cells(i, 3) = programN Then
                If rng Is Nothing Then
                    Set rng = test.Range(Cells(i, 1), Cells(i, 78))

                    MsgBox "Range was set"
                    Exit For
                Else
                    Set rng = Union(rng, ActiveSheet.Range(Cells(i, 1), Cells(i, 78)))

                    MsgBox "Range was set"
                    Exit For
                End If
         Else
             'something
         End If

      Next i

      'For Each Cell In Program

          'If Cell = programN Then
              'If rng Is Nothing Then
                'Set rng = Cell.Range(Cells(ActiveCell.Row, 1), Cells(ActiveCell.Row, 78))
              'Else
                'r = ActiveCell.Row
                'Set rng = Union(rng, Cell.Range(Cells(ActiveCell.Row, 1), Cells(ActiveCell.Row, 78)))
              'End If
          'Else
              'cell.Font.ColorIndex = 3

      'End If

      'Next
      Dim ws As Worksheet: Set ws = newBook.Worksheets(1)
      erow = ws.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
      If Not rng Is Nothing Then
        rng.Copy
      Else
        MsgBox "rng was not set in the for loop"
      End If
      ws.Cells(erow, 1).PasteSpecial
      'ws.Cells(erow, 1).PasteSpecial xlPasteFormats
      'ws.Cells(erow, 1).PasteSpecial xlPasteValues
      ws.Columns("A:L").ColumnWidth = 14
      ws.Columns("C").AutoFit
      ws.Columns("N:CM").ColumnWidth = 14
      'Set wbThis = Workbooks("TS L2L3v111.xlsm")

      'Dim test As Worksheet: Set test = wbThis.Worksheets(4)

      test.Rows(2).Copy
      ws.Cells(1, 1).PasteSpecial
      ws.Columns("F:K").Columns.Group
      ws.Columns("F:K").EntireColumn.Hidden = True
      ws.Columns("R:Z").Columns.Group
      ws.Columns("R:Z").EntireColumn.Hidden = True
      ws.Columns("AH:AP").Columns.Group
      ws.Columns("AH:AP").EntireColumn.Hidden = True
      ws.Columns("AX:BF").Columns.Group
      ws.Columns("AX:BF").EntireColumn.Hidden = True
      ws.Columns("BJ:BN").Columns.Group
      ws.Columns("BJ:BN").EntireColumn.Hidden = True
      ws.Columns("BP:CA").Columns.Group
      ws.Columns("BP:CA").EntireColumn.Hidden = True
      ws.Range("A1", "CM1").End(xlUp).AutoFilter 1
      ActiveWindow.SplitColumn = 13
      ActiveWindow.FreezePanes = True
      ws.Columns("CW:FX").Clear
      ws.Cells.Validation.Delete
      newBook.Save
      newBook.Close
      'Set newBook = Workbooks.Open("C:\Users\" & userID & "\Desktop\" & programN & ".xlsm")
      'Dim test1 As Worksheet: Set test1 = newBook.Worksheets(1)
      'test1.ScrollArea = "$A$1:$CV$2000"
     ' newBook.Save
      'newBook.Close

  'Next programN
End Sub

【问题讨论】:

  • 试过了。没用:/
  • 注意 你的代码 test.Range(Cells(i, 1), Cells(i, 78)) 实际上是 test.Range(ActiveSheet.Cells(i, 1), ActiveSheet.Cells(i, 78)) 这不是你想要的。您希望test.Range(test.Cells(i, 1), test.Cells(i, 78)) 或更好的test.Range("A1").Resize(2000,78) 获得整张桌子。
  • 简而言之,不要使用Range(Cells(),Cells()) 来选择多个值。使用Range("A2").Cell(i,1).Resize(n,m) 类型的操作在“A2”下的第 i 行选取 n×m 个值。
  • 我下周二也试试。谢谢!

标签: vba excel


【解决方案1】:

For i = 1 To 2000 之前尝试添加wbThis.Activate。有时,如果工作簿未先处于活动状态,则不允许您在其中进行操作。

编辑:

您还使用了ActiveSheet,这可能很危险。鉴于您正在创建工作簿并在此行之前添加工作表,我会质疑实际的“活动工作表”是什么。如果您改为在此处引用工作表名称,这是一种更好的做法,可确保您使用的是预期工作表。

【讨论】:

  • 下周二我会在工作中试一试,然后告诉你进展如何。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-09
  • 2016-09-17
  • 1970-01-01
  • 2016-04-25
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
相关资源
最近更新 更多