Consulting

Results 1 to 3 of 3

Thread: Loop thru all sheets and copy a value

  1. #1
    VBAX Newbie
    Joined
    Oct 2014
    Posts
    5
    Location

    Loop thru all sheets and copy a value

    Hi,

    I have the following, and want it loop through the sheets, and in each sheet, copy the value in B1 down the rest of column B (active cells). However it is copying the value in B1 sheet 1 to all the sheets. But this is not what I want. In sheet 2 , I want B1 from sheet 2 copied down. In sheet 3 , I want B1 from sheet 3 copied down, ect. Appreciate any help..thanks!


    Sub AddColumn()
    
    
    Dim sht As Worksheet
    Dim Lastrow As Long
    Dim Pasterange As String
    Dim cnt As Integer
    
    
    For Each sht In ActiveWorkbook.Worksheets
        sht.Range("A1").EntireColumn.Insert xlShiftToRight
        sht.Cells(1, 1) = "=Left(R2C13,13)"
        sht.Cells(1, 2) = "=right(R3C3,11)"
        Lastrow = Range("C" & Rows.Count).End(xlUp).Row
        cnt = sht.Cells.SpecialCells(xlCellTypeLastCell).Row
        Let Pasterange = "B2:" & "B" & cnt
        Range("B1").Select
        Selection.Copy
        Range(Pasterange).Select
        sht.Range(Pasterange).PasteSpecial Paste:=xlValues
    Next sht
    
    
    End Sub
    Last edited by mdmackillop; 08-24-2017 at 10:22 AM. Reason: Code tags added

  2. #2
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    You need to qualify all your ranges etc.
    Sub AddColumn()
        Dim sht As Worksheet
        'Dim Lastrow As Long
        Dim Pasterange As Range
        Dim cnt As Integer
        For Each sht In ActiveWorkbook.Worksheets
            With sht
            .Range("A1").EntireColumn.Insert xlShiftToRight
            .Cells(1, 1) = "=Left(R2C13,13)"
            .Cells(1, 2) = "=right(R3C3,11)"
            'Lastrow = .Range("C" & Rows.Count).End(xlUp).Row
            cnt = sht.Cells.SpecialCells(xlCellTypeLastCell).Row
            Set Pasterange = .Range("B2:" & "B" & cnt)
            .Range("B1").Copy
            Pasterange.PasteSpecial Paste:=xlValues
            End With
        Next sht
    End Sub
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  3. #3
    VBAX Newbie
    Joined
    Oct 2014
    Posts
    5
    Location
    thank you mdmackillop!!!! works great!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •