Consulting

Results 1 to 4 of 4

Thread: VBA S.O.S.

  1. #1
    VBAX Newbie
    Joined
    Aug 2014
    Posts
    4
    Location

    VBA S.O.S.

    Here's the breakdown

    - Header is stored in Sheet1, a2:ch2
    - Sheet 2 and Sheet 3 do not have headers
    - Sheet 3 may exist in some workbooks, but might not in others.

    - Want to copy header in Sheet 1 to Sheet 2 and 3, and shift down all the rest

    So far, I've got this......

    ----
    Sub Add_Header()
        Dim wBook As Workbook
        Set wBook = Workbooks.Open("C:\CCT\TEMP\T\ABCDEFG.xls")
        Sheets("Sheet1").Select
        Range("A1:CH1").Select
        Selection.Copy
        Sheets("Sheet2").Select
        Selection.Insert Shift:=xlDown
        Sheets("Sheet1").Select
        Range("A1:CH1").Select
        Selection.Copy
        Sheets("Sheet2").Select
        Selection.Insert Shift:=xlDown
        wBook.Save
        Sheets("Sheet3").Select
        Range("A1").Select
        Selection.Insert Shift:=xlDown
        wBook.Save
    End Sub

    ----

    Getting '1004 errors.. =(


    Thanks in advance
    Last edited by Bob Phillips; 08-26-2014 at 12:37 AM. Reason: Added VBA tags

  2. #2
    try like
    dim sht as worksheet
    for each sht in thisworkbook.worksheets
       if sht.name = "Sheet3" then exit for
    next
    if sht is nothing then thisworkbook.sheets.add.name = "Sheet3"
    for s = 2 to 3
       sheets("sheet" & s).cells(1, 1).entirerow.insert
       sheets("sheet" & s).range("a1:ch1").value = sheets("sheet1").range("a1:ch1")
    next
    this avoids selecting cells and changing between sheets, checks if sheet3 exists and adds if not

  3. #3
    VBAX Newbie
    Joined
    Aug 2014
    Posts
    4
    Location
    Thanks Westconn1!!!

    For my code, there are workbooks with 2 sheets (sheet1, sheet2) and some with 3 (sheet1,sheet2,sheet3).. I'm just looking to add the Header from sheet1 to sheet2 and sheet3 (if sheet3 exists), if not only add the header to sheet2, instead of adding a new sheet3

  4. #4
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    Keep it simple

    Worksheets("Sheet2").Rows(1).Insert
    Worksheets("Sheet1").Range("A1:CH1").Copy Worksheets("Sheet2").Range("A1")
    On Error Resume Next
    Set sh = Worksheets("Sheet3")
    On Error Goto 0
    If Not sh Is Nothing Then
        sh.Rows(1).Insert
        Worksheets("Sheet1").Range("A1:CH1").Copy sh.Range("A1")
    End If
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

Posting Permissions

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