Question

Subdirectory traverse and append to single file - II

Asked by: sajuks

With Reference To
http://www.experts-exchange.com/Applications/MS_Office/Excel/Q_21953044.html

The above macro met my initial requirement. But it fails when i try to append when one of the columns is in date format and
it also gives problem with the number format.
In short if one of the columns contains the date like

Date
12-May-2006
11-May-2006
19-Mar-2006

it shows its numeric value.
Similarly is there a way that when i copy i can show the number with only two decimal values
So for ex, when i run the macro i get
14.56777 when actually i need 14.56

It seems that the format that has been set in the initial worksheets do not get copied.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-08-29 at 04:17:31ID21970792
Tags

excel

,

traverse

Topic

Microsoft Excel Spreadsheet Software

Participating Experts
1
Points
500
Comments
37

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. XL Print worksheet  only if criteria met
    A workbook contains 50 sheets. Based on monthly input, not all will be printed. If there is a Print/NoPrint cell in each sheet, can the worksheets to be printed be automated? Thanks - Bob Snare
  2. vba code to delete named ranges if criteria is not met from a…
    I have a worksheet (short quote)that contains linked data from user input on another worksheet (input). Depending upon what they choose some of the information on this worksheet (short quote) does not need to be displayed on the final view so what I was going to do is divide ...
  3. Macro dropping decimal
    Hello Experts, I am running a macro in Excel. I have a declared variable as a long. I make the variable equal to the value of an active cell (a decimal value). Result always rounds to nearest whole number (e.g. 44.95-->45). Have tried number format on the cell before...
  4. Macro to change color
    Hi, I tried using conditional formatting but it doesn't seem to reformat if a cell value changes, so I need help with a macro. P|Q|R Date1|Date2|Met Column R for met has a formula that shows 1 if p<=q and 0 if p> q and blank if q is blank (this works OK) How do I fo...
  5. Special operations with data according to conditions to be …
    I would like to ask for a VBA code example for developing the programmed data handling on an Excel worksheet. This is the explanation of what is wanted: 1) “Sheet1” is the active worksheet. 2) Start by looking on column “A”, until text “ABC” is found. 3) Once this is met, n...
  6. INSERT A LINE AND COLOR IT DARK RED WHEN A GIVEN C…
    I want a macro to insert a line and color it red for columns A:K when the date in column G is > 12 weeks (84 days) from today ("today" being dynamic). I only want it to insert a line the FIRST time the condition is met. Any questions? You guys are all geniuses....

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: roryaPosted on 2006-08-29 at 04:24:01ID: 17410784

Hi,
Try this:

Sub ListSubFiles(strParentFolder As String)
    Dim fs As FileSearch
    Dim lngCounter As Long, lngRow As Long, lngOutputRow As Long
    Dim wbk As Workbook, wks1 As Worksheet, wks2 As Worksheet, wksSummary As Worksheet
    Dim rngData As Range, rngCell As Range
    Dim strCompany As String
    Application.ScreenUpdating = False
    Set wksSummary = ActiveWorkbook.ActiveSheet
    lngOutputRow = 1
    Set fs = Application.FileSearch
    With fs
        .NewSearch
        .LookIn = strParentFolder
        .SearchSubFolders = True
        .FileName = "*.xls"
        .MatchTextExactly = True
        .FileType = msoFileTypeExcelWorkbooks
        .Execute
        ' Loop through all the found files
        For lngCounter = 1 To .FoundFiles.Count
            Set wbk = Workbooks.Open(.FoundFiles(lngCounter))
            Set wks1 = wbk.Sheets("Detail sheet")
            Set wks2 = wbk.Sheets("Summary sheet")
            strCompany = wks2.Range("C3")
            ' Assumes there will always be data in column 1
            If lngCounter = 1 Then
                Set rngData = Intersect(wks1.UsedRange, wks1.Columns(1))
            Else
                Set rngData = Intersect(wks1.UsedRange, wks1.Range("A2:A65536"))
            End If
            For Each rngCell In rngData
                ' Write columns 1, 2 and 4 and company name to sheet 1 of this workbook
                rngCell.Copy wksSummary.Cells(lngOutputRow, 1)
                rngCell.Offset(0, 1).Copy wksSummary.Cells(lngOutputRow, 2)
                rngCell.Offset(0, 3).Copy wksSummary.Cells(lngOutputRow, 3)
                If lngOutputRow > 1 Then wksSummary.Cells(lngOutputRow, 4) = strCompany
                lngOutputRow = lngOutputRow + 1
            Next rngCell
            wbk.Close False
        Next lngCounter
        Set rngData = Nothing
        Set wks1 = Nothing
        Set wks2 = Nothing
        Set wbk = Nothing
    End With
    Set fs = Nothing
    Application.ScreenUpdating = True
End Sub


HTH
Rory

 

by: sajuksPosted on 2006-08-29 at 04:31:25ID: 17410826

thats too fast Rory, will give you a feedback in a few hours.

 

by: roryaPosted on 2006-08-29 at 04:37:02ID: 17410856

No worries. As you can see, that basically does a copy and paste operation so you will get exactly what was there before including formatting. If you just wanted to copy over the displayed values, you could use:

Sub ListSubFiles(strParentFolder As String)
    Dim fs As FileSearch
    Dim lngCounter As Long, lngRow As Long, lngOutputRow As Long
    Dim wbk As Workbook, wks1 As Worksheet, wks2 As Worksheet, wksSummary As Worksheet
    Dim rngData As Range, rngCell As Range
    Dim strCompany As String
    Application.ScreenUpdating = False
    Set wksSummary = ActiveWorkbook.ActiveSheet
    lngOutputRow = 1
    Set fs = Application.FileSearch
    With fs
        .NewSearch
        .LookIn = strParentFolder
        .SearchSubFolders = True
        .FileName = "*.xls"
        .MatchTextExactly = True
        .FileType = msoFileTypeExcelWorkbooks
        .Execute
        ' Loop through all the found files
        For lngCounter = 1 To .FoundFiles.Count
            Set wbk = Workbooks.Open(.FoundFiles(lngCounter))
            Set wks1 = wbk.Sheets("Detail sheet")
            Set wks2 = wbk.Sheets("Summary sheet")
            strCompany = wks2.Range("C3")
            ' Assumes there will always be data in column 1
            If lngCounter = 1 Then
                Set rngData = Intersect(wks1.UsedRange, wks1.Columns(1))
            Else
                Set rngData = Intersect(wks1.UsedRange, wks1.Range("A2:A65536"))
            End If
            For Each rngCell In rngData
                ' Write columns 1, 2 and 4 and company name to sheet 1 of this workbook
                wksSummary.Cells(lngOutputRow, 1) = rngCell.Text
                wksSummary.Cells(lngOutputRow, 2) = rngCell.Offset(0, 1).Text
                wksSummary.Cells(lngOutputRow, 3) = rngCell.Offset(0, 3).Text
                If lngOutputRow > 1 Then wksSummary.Cells(lngOutputRow, 4) = strCompany
                lngOutputRow = lngOutputRow + 1
            Next rngCell
            wbk.Close False
        Next lngCounter
        Set rngData = Nothing
        Set wks1 = Nothing
        Set wks2 = Nothing
        Set wbk = Nothing
    End With
    Set fs = Nothing
    Application.ScreenUpdating = True
End Sub

Regards,
Rory

 

by: sajuksPosted on 2006-08-29 at 20:57:54ID: 17417050

The above doesnt work with the date field...
The data in the excel sheet is for example 24/09/1980 which is displayed as 24-Sep-1980 and whn it is copied to the new sheet using the macro it gets displayed as 29488 and if i  try to edit the cell it shoes the value of 24/09/1980 .
There is one more modificn which i require is that , there are two date fields and in one column i want to get the age in that.
For ex: Col E and Col F contain the dates 12/01/2001 and 25/06/2006 i want to get the difference in age in those columns.

 

by: roryaPosted on 2006-08-30 at 00:53:37ID: 17418101

Which version did you try? (Both?)
What exactly do you mean when you say you want the difference in age? Do you want the difference in days, or months, or something else?
Rory

 

by: sajuksPosted on 2006-08-30 at 01:11:46ID: 17418205

I tried both.
but am sticking with the second one
wksSummary.Cells(lngOutputRow, 1) = rngCell.Text
wksSummary.Cells(lngOutputRow, 2) = rngCell.Offset(0, 1).Text
wksSummary.Cells(lngOutputRow, 3) = rngCell.Offset(0, 3).Text

or ex: Col E and Col F contain the dates 12/01/2001 and 25/06/2006
where Col E is the bithdate and Col F is the start date, i want to know the Age for that person as on the value in Col F.
so for ex in the above scenario it would be five (5) years

 

by: roryaPosted on 2006-08-30 at 01:19:42ID: 17418247

OK and where do you want it put?
I'm surprised the Copy version didn't work, since it should copy the whole cell including formatting. Are all the date fields in a specific place? If so, the code could simply format those columns at the end.
Regards,
Rory

 

by: sajuksPosted on 2006-08-30 at 01:28:09ID: 17418283

"OK and where do you want it put?"
Lets say the last column .

"Are all the date fields in a specific place? If so, the code could simply format those columns at the end."
Are you asking whether the date field are in  specific columns ? If so, rite now they are in Column C,D and F.

Both versions of your code displays the date fields in excel serial number
24/09/1980 as 29488
04/04/1980 as 29315
and so on

 

 

by: roryaPosted on 2006-08-30 at 01:54:38ID: 17418430

Now I am confused - the code only looks at columns A, B and D so where do C and F come into it?
Regards,
Rory

 

by: sajuksPosted on 2006-08-30 at 02:21:50ID: 17418551

Its just an example.
For the code sake, lets assume that the date fields are in B & D

 

by: roryaPosted on 2006-08-30 at 02:38:38ID: 17418612

OK then, try this:

Sub ListSubFiles(strParentFolder As String)
    Dim fs As FileSearch
    Dim lngCounter As Long, lngRow As Long, lngOutputRow As Long
    Dim wbk As Workbook, wks1 As Worksheet, wks2 As Worksheet, wksSummary As Worksheet
    Dim rngData As Range, rngCell As Range
    Dim strCompany As String
    Application.ScreenUpdating = False
    Set wksSummary = ActiveWorkbook.ActiveSheet
    lngOutputRow = 1
    Set fs = Application.FileSearch
    With fs
        .NewSearch
        .LookIn = strParentFolder
        .SearchSubFolders = True
        .FileName = "*.xls"
        .MatchTextExactly = True
        .FileType = msoFileTypeExcelWorkbooks
        .Execute
        ' Loop through all the found files
        For lngCounter = 1 To .FoundFiles.Count
            Set wbk = Workbooks.Open(.FoundFiles(lngCounter))
            Set wks1 = wbk.Sheets("Detail sheet")
            Set wks2 = wbk.Sheets("Summary sheet")
            strCompany = wks2.Range("C3")
            ' Assumes there will always be data in column 1
            If lngCounter = 1 Then
                Set rngData = Intersect(wks1.UsedRange, wks1.Columns(1))
            Else
                Set rngData = Intersect(wks1.UsedRange, wks1.Range("A2:A65536"))
            End If
            For Each rngCell In rngData
                ' Write columns 1, 2 and 4 and company name to sheet 1 of this workbook
                With wksSummary.Cells(lngOutputRow, 1)
                      .Value = rngCell
                      .Numberformat = "#,##0.00;-#,##0.00;0.00"
                End With
                With wksSummary.Cells(lngOutputRow, 2)
                      .Value = rngCell.Offset(0, 1)
                      .NumberFormat = "dd-mmm-yyyy"
                End With
                With wksSummary.Cells(lngOutputRow, 3)
                      .Value = rngCell.Offset(0, 3)
                      .NumberFormat = "dd-mmm-yyyy"
                End With
                If lngOutputRow > 1 Then
                     With wksSummary.Cells(lngOutputRow, 4)
                          .Value = strCompany
                          .Offset(0,1).FormulaR1C1 = "=Year(RC[-2])-year(RC[-3])-if(month(RC[-2])<month(RC[-3]),1,0)"
                          .Offset(0,1).NumberFormat = "0 ""years"""
                     End With
                End If
                lngOutputRow = lngOutputRow + 1
            Next rngCell
            wbk.Close False
        Next lngCounter
        Set rngData = Nothing
        Set wks1 = Nothing
        Set wks2 = Nothing
        Set wbk = Nothing
    End With
    Set fs = Nothing
    Application.ScreenUpdating = True
End Sub

Regards,
Rory

 

by: sajuksPosted on 2006-08-30 at 05:54:57ID: 17419896

Still not working.
Please check the sample upload file that i have uploaded at
http://rapidshare.de/files/31310823/Sample.xls

The format is not as we are working on..but this is the actual data that we are trying to append.
All the columns that are shown are needed. ( There are more but i have deleted it )

 

by: roryaPosted on 2006-08-30 at 07:29:18ID: 17420641

Try this:

Sub ListSubFiles(strParentFolder As String)
    Dim fs As FileSearch
    Dim lngCounter As Long, lngRow As Long, lngOutputRow As Long
    Dim wbk As Workbook, wks1 As Worksheet, wks2 As Worksheet, wksSummary As Worksheet
    Dim rngData As Range, rngCell As Range
    Dim strCompany As String
    Application.ScreenUpdating = False
    Set wksSummary = ActiveWorkbook.ActiveSheet
    lngOutputRow = 1
    Set fs = Application.FileSearch
    With fs
        .NewSearch
        .LookIn = strParentFolder
        .SearchSubFolders = True
        .FileName = "*.xls"
        .MatchTextExactly = True
        .FileType = msoFileTypeExcelWorkbooks
        .Execute
        ' Loop through all the found files
        For lngCounter = 1 To .FoundFiles.Count
            Set wbk = Workbooks.Open(.FoundFiles(lngCounter))
            Set wks1 = wbk.Sheets("Detail sheet")
            Set wks2 = wbk.Sheets("Summary sheet")
            strCompany = wks2.Range("C3")
            ' Assumes there will always be data in column 1
            If lngCounter = 1 Then
                Set rngData = Intersect(wks1.UsedRange, wks1.Range("A3:A65536"))
            Else
                Set rngData = Intersect(wks1.UsedRange, wks1.Range("A4:A65536"))
            End If
            For Each rngCell In rngData
                ' Write columns 1, 2 and 4 and company name to sheet 1 of this workbook
                If Len(rngCell) > 0 Then
                    With wksSummary.Cells(lngOutputRow, 1)
                          .Value = rngCell
                          .NumberFormat = "#,##0.00;-#,##0.00;0.00"
                    End With
                    With wksSummary.Cells(lngOutputRow, 2)
                          .Value = rngCell.Offset(0, 1)
                          .NumberFormat = "dd-mmm-yyyy"
                    End With
                    With wksSummary.Cells(lngOutputRow, 3)
                          .Value = rngCell.Offset(0, 3)
                          .NumberFormat = "dd-mmm-yyyy"
                    End With
                    If lngOutputRow > 1 Then
                         With wksSummary.Cells(lngOutputRow, 4)
                              .Value = strCompany
                              .Offset(0, 1).Value = DatePart("yyyy", rngCell.Offset(0, 3)) - DatePart("yyyy", rngCell.Offset(0, 2)) - IIf(DatePart("m", rngCell.Offset(0, 3)) < DatePart("m", rngCell.Offset(0, 2)), 1, 0)
                              .Offset(0, 1).NumberFormat = "0 ""years"""
                         End With
                    End If
                    lngOutputRow = lngOutputRow + 1
                End If
            Next rngCell
            wbk.Close False
        Next lngCounter
        Set rngData = Nothing
        Set wks1 = Nothing
        Set wks2 = Nothing
        Set wbk = Nothing
    End With
    Set fs = Nothing
    Application.ScreenUpdating = True
End Sub


Regards,
Rory

PS "Not working" is not that useful - if you can tell me in what way it is failing that will speed things up!

 

by: sajuksPosted on 2006-08-31 at 00:43:29ID: 17426867

"PS "Not working" is not that useful - if you can tell me in what way it is failing that will speed things up!"

Rory, i am still stuck with the one and the same problem , the dates are not displayed properly. So i didnt mention it again. Sorry.

 

by: sajuksPosted on 2006-08-31 at 01:24:13ID: 17427131

Still no change . The dates dont appear in the date format and are appearing as numbers

Emp No      Emp Name      DOJ            
40      B O B                   38777      ( if i click on the DOJ row cell it shows the value 3/1/2006 )
03      C O D                  38824      ( here it shows the value 4/17/2006)
14      D J                    38831      (4/24/2006)

 

by: roryaPosted on 2006-08-31 at 01:42:31ID: 17427253

Well, I confess I'm stumped - I tested that several times on the sample file you provided and it *always* formatted the dates. However, I note your comment: "The format is not as we are working on..but this is the actual data that we are trying to append." Does this mean you are amending the code to fit the actual format you are working on?
Regards,
Rory

 

by: sajuksPosted on 2006-08-31 at 01:45:52ID: 17427270

What i meant is i have not given the whole data which spans 20-30 columns. The format is the same.

"Does this mean you are amending the code to fit the actual format you are working on?"
We are adding the number of cells and thats it. The dateformat is as in the uploaded file.


We are working with excel 2002. Would that make any difference ?

 

by: roryaPosted on 2006-08-31 at 01:52:00ID: 17427302

I am using XL2002 as well.
The only thing I can think of right now is that there may be something about the worksheet you are copying to - is this a blank new workbook or a pre-existing one?
Regards,
Rory

 

by: sajuksPosted on 2006-08-31 at 01:56:20ID: 17427331

I created a new excel file
COpied the above macro into it.
And ran it from there.
So its a blank new workbook.
I am okay with testing it by copying it to a new excel file if you think that might make a difference and as long as you supply the code for it :-)

 

by: roryaPosted on 2006-08-31 at 02:05:07ID: 17427383

If you ran it already from a new blank workbook then that shouldn't be the problem. Any chance that you could post a copy of the workbook you have run it from (where it didn't work), including the code, and a full sample of the dataset it runs against - you can reduce the number of rows, but please keep all the columns? That way I can just double-check that I haven't missed anything obvious!
Regards,
Rory

 

by: sajuksPosted on 2006-08-31 at 02:26:13ID: 17427488

 

by: sajuksPosted on 2006-08-31 at 02:33:03ID: 17427507

Got it working. I made active another worksheet and it executed properly.
Let me just do some more runs and i will close this question soon.

 

by: roryaPosted on 2006-08-31 at 02:40:43ID: 17427536

Sounds promising! Fingers crossed...
Rory

 

by: sajuksPosted on 2006-08-31 at 02:51:39ID: 17427562

One problem in getting the age ( date difference)
The dates are displayed as 24-Sep-80 and 01-Mar-06
so when i use the code
wksSummary.Cells(lngOutputRow, 10) = DatePart("yy", rngCell.Offset(0, 8)) - DatePart("yy", rngCell.Offset(0, 3)) - IIf(DatePart("m", rngCell.Offset(0, 8)) < DatePart("m", rngCell.Offset(0, 3)), 1, 0)
i get a Type mismatch error. ( the values that they get are the proper date fields i confirmed that )
The dates are in the columns C and H.
So i want to paste the difference between the too in column J .

 

by: roryaPosted on 2006-08-31 at 02:59:38ID: 17427585

"yy" is not a valid argument for the DatePart function - you need to use "yyyy". You may also need to doublecheck that all the cells in question contain valid dates - if any are blank, you would get that error.
Regards,
Rory

 

by: sajuksPosted on 2006-08-31 at 03:04:23ID: 17427599

it was yyyy, since the date is dipslayed as 24-Sep-80 , i used yy.
no dates are blank . i checked with only three records

 

by: roryaPosted on 2006-08-31 at 03:08:21ID: 17427612

I just noticed you said the dates are in C and H - the offsets you are using are 3 and 8, which actually gives you columns D and I, since 3 to the right from column 1 is actually column 4 not column 3 and similarly for the 8. Try changing the offsets to 2 and 7.
HTH
Rory

 

by: sajuksPosted on 2006-08-31 at 03:11:43ID: 17427623

Doh! This is breaking me up.
sorry.

 

by: roryaPosted on 2006-08-31 at 03:21:35ID: 17427682

no problem - been there, done that! :-)
Rory

 

by: sajuksPosted on 2006-08-31 at 03:53:43ID: 17427853

thanks that works.
Would it be possible to have the output to be copied to another file instead of having it be appended where the macro is run ?

 

by: roryaPosted on 2006-08-31 at 03:58:17ID: 17427867

Do you want it to be a new file, or a specified file?
Regards,
Rory

 

by: roryaPosted on 2006-08-31 at 03:59:59ID: 17427877

PS As it is currently, the code outputs the data to whatever is the activesheet when you run the macro. So you can just open a new workbook and run the code.
Rory

 

by: sajuksPosted on 2006-08-31 at 05:10:41ID: 17428190

"the code outputs the data to whatever is the activesheet when you run the macro"
 i would like it to o/p in a new file.

 

by: roryaPosted on 2006-08-31 at 05:20:11ID: 17428238

Change this line (near the top):
    Set wksSummary = ActiveWorkbook.ActiveSheet

to this:
    Set wksSummary = Workbooks.Add.Sheets(1)

HTH
Rory

 

by: sajuksPosted on 2006-08-31 at 05:31:13ID: 17428301

'Set wksSummary = Workbooks.Add.Sheets(1)
I was talking about a new excel file and not a new excel sheet.
Say if i run this from macro.xls it should ask for and save it in a file say userprefernce.xls.
Would that be possible ?

 

by: roryaPosted on 2006-08-31 at 05:40:20ID: 17428361

That line creates a new workbook and sets the output sheet as the first sheet in that new workbook.
This version prompts for a save name and location for the new workbook:

Sub ListSubFiles(strParentFolder As String)
    Dim fs As FileSearch
    Dim lngCounter As Long, lngRow As Long, lngOutputRow As Long
    Dim wbk As Workbook, wks1 As Worksheet, wks2 As Worksheet, wksSummary As Worksheet
    Dim rngData As Range, rngCell As Range
    Dim strCompany As String
    Dim varFileName

    Application.ScreenUpdating = False
    Set wksSummary = Workbooks.Add.Sheets(1)
    lngOutputRow = 1
    Set fs = Application.FileSearch
    With fs
        .NewSearch
        .LookIn = strParentFolder
        .SearchSubFolders = True
        .FileName = "*.xls"
        .MatchTextExactly = True
        .FileType = msoFileTypeExcelWorkbooks
        .Execute
        ' Loop through all the found files
        For lngCounter = 1 To .FoundFiles.Count
            Set wbk = Workbooks.Open(.FoundFiles(lngCounter))
            Set wks1 = wbk.Sheets("Detail sheet")
            Set wks2 = wbk.Sheets("Summary sheet")
            strCompany = wks2.Range("C3")
            ' Assumes there will always be data in column 1
            If lngCounter = 1 Then
                Set rngData = Intersect(wks1.UsedRange, wks1.Range("A3:A65536"))
            Else
                Set rngData = Intersect(wks1.UsedRange, wks1.Range("A4:A65536"))
            End If
            For Each rngCell In rngData
                ' Write columns 1, 2 and 4 and company name to sheet 1 of this workbook
                If Len(rngCell) > 0 Then
                    With wksSummary.Cells(lngOutputRow, 1)
                          .Value = rngCell
                          .NumberFormat = "#,##0.00;-#,##0.00;0.00"
                    End With
                    With wksSummary.Cells(lngOutputRow, 2)
                          .Value = rngCell.Offset(0, 1)
                          .NumberFormat = "dd-mmm-yyyy"
                    End With
                    With wksSummary.Cells(lngOutputRow, 3)
                          .Value = rngCell.Offset(0, 3)
                          .NumberFormat = "dd-mmm-yyyy"
                    End With
                    If lngOutputRow > 1 Then
                         With wksSummary.Cells(lngOutputRow, 4)
                              .Value = strCompany
                              .Offset(0, 1).Value = DatePart("yyyy", rngCell.Offset(0, 3)) - DatePart("yyyy", rngCell.Offset(0, 2)) - IIf(DatePart("m", rngCell.Offset(0, 3)) < DatePart("m", rngCell.Offset(0, 2)), 1, 0)
                              .Offset(0, 1).NumberFormat = "0 ""years"""
                         End With
                    End If
                    lngOutputRow = lngOutputRow + 1
                End If
            Next rngCell
            wbk.Close False
        Next lngCounter
       varFileName = application.getsaveasfilename(fileFilter:="Excel Files (*.xls), *.xls")
      if varFileName <> False then
           wksSummary.Parent.SaveAs varFileName
      end if

        Set rngData = Nothing
        Set wks1 = Nothing
        Set wks2 = Nothing
        Set wbk = Nothing
    End With
    Set fs = Nothing
    Application.ScreenUpdating = True
End Sub


HTH
Rory

 

by: sajuksPosted on 2006-09-02 at 19:23:48ID: 17444165

Sorry for not closing this earlier. Am stuck wih a few other deadlines. Tnx

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...