473,399 Members | 2,159 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

How can I have Excel record file names from a folder and count the rows within?

I had this code ages ago and saved it someplace safe. So safe, I lost it, and now I cannot recall how I did it. I went accross the internet to find similar code and did find this code, which is pretty much almost where I am trying to get to. Basically, the code attached will tell me how many records are in the file I tell it, through an alert box. What I would like to do is have the program look in a folder I designate and find each file, record the filename in Cell A2 and the record count in B2, then the next file name in the folder would go into A3 and record count in B3 and so on.

Any advice on how to proceed would be greatly appreciated. I just feel like I am just missing something basic as far as the record the file stuff in excel.

Expand|Select|Wrap|Line Numbers
  1. Sub ReadNoLines_text()
  2.  
  3. 'Dimension Variables
  4. Dim ResultStr As String
  5. Dim FileName As String
  6. Dim FileNum As Integer
  7. Dim CountLines As Double
  8.  
  9. 'Ask User for File's Name
  10. FileName = InputBox("Please enter the Text File's name")
  11. 'Check for no entry
  12. If FileName = "" Then End
  13. 'Get Next Available File Handle Number
  14. FileNum = FreeFile()
  15. 'Open Text File For Input
  16. Open FileName For Input As #FileNum
  17. 'Set The CountLines to 1
  18. CountLines = 1
  19. 'Loop Until the End Of File Is Reached
  20. Do While Seek(FileNum) <= LOF(FileNum)
  21. Line Input #FileNum, ResultStr
  22. 'Increment the CountLines By 1
  23. CountLines = CountLines + 1
  24. 'Start Again At Top Of 'Do While' Statement
  25. Loop
  26.  
  27. 'Close The Open Text File
  28. Close
  29. MsgBox "Number of lines for " & FileName & " = " & CountLines - 1
  30. End Sub
  31.  
Sep 11 '14 #1

✓ answered by twinnyfo

theberner,

I think the key is to use the Dir() function. Identify the folder, and then the first time, use Dir("[FolderPath]") to get the name of the first file. Manipulate that file as needed, then when you execute Dir() again (no arguments), you will get the name of the next file.

In terms of automating Excel, there are many ways to do that, and this forum should have multiple threads to assist. I wish I had some very basic code to get you started (but I may try to post some for you shortly).

7 1874
twinnyfo
3,653 Expert Mod 2GB
theberner,

I think the key is to use the Dir() function. Identify the folder, and then the first time, use Dir("[FolderPath]") to get the name of the first file. Manipulate that file as needed, then when you execute Dir() again (no arguments), you will get the name of the next file.

In terms of automating Excel, there are many ways to do that, and this forum should have multiple threads to assist. I wish I had some very basic code to get you started (but I may try to post some for you shortly).
Sep 11 '14 #2
twinnyfo
3,653 Expert Mod 2GB
Here is some basic Code to get you started. NB, I am using this from the MS Access VBA environment.

Expand|Select|Wrap|Line Numbers
  1. Public Function OpenExcel()
  2.     Dim xlApp As Excel.Application
  3.     Dim xlWB As Excel.Workbook
  4.     Dim xlSheet As Excel.Worksheet
  5.     Set xlApp = CreateObject("Excel.Application")
  6.     xlApp.Visible = True
  7.     Set xlWB = xlApp.Workbooks.Add
  8.     xlWB.Activate
  9.     Set xlSheet = xlWB.ActiveSheet
  10.     xlSheet.Cells(Row, Column) = "Enter Text Here"
  11.     xlSheet.Application.ActiveWorkbook.SaveAs "Test.xlsx"
  12.     xlSheet.Application.ActiveWorkbook.Close
  13.     Set xlSheet = Nothing
  14.     Set xlApp = Nothing
  15. End Function
Sep 11 '14 #3
Thank you. I will give it a try and see if I can get it to wor.
Sep 11 '14 #4
ok. Not sure if i can reply to one where i picked a solution, but just in case. I made some updates and also found part of the old stuff i had. It does not work exactly and i when i step through the process i think it's the way i define the folder path. I want the excel to look in the same folder it is in. Just seems easier that way. But my setup seems to be missing something.

Expand|Select|Wrap|Line Numbers
  1. Option Compare Text
  2.  
  3. Sub Checker2()
  4. '
  5. '
  6.  
  7. fRowNum = 2
  8. fColumNum = 2
  9. fTRow = 2
  10. fWorkbookName = ThisWorkbook.Name
  11.  
  12.     fName = Cells(1, 1)
  13.     fpathname = ActiveWorkbook.Path & "\" & fName & "\"
  14.  
  15.     fFileName = Dir(fpathname & "*.txt")
  16.  
  17.     Do While fFileName <> ""
  18.             Workbooks.Open (fpathname & fFileName)
  19.             Range("A1").Select
  20.             Selection.End(xlDown).Select
  21.             fRow = ActiveCell.Row
  22.  
  23.             Workbooks(fWorkbookName).Activate
  24.  
  25.             Range("E2").Select
  26.             If Cells(2, 5).Value = "" Then
  27.                                 fRowB = 1
  28.             Else
  29.                 Selection.End(xlDown).Select
  30.                 fRowB = ActiveCell.Row
  31.             End If
  32.             Range("E2 : E" & fRowB).Select
  33.             Selection.ClearContents
  34.  
  35.  
  36.             Workbooks.Open (fpathname & fFileName)
  37.             Range("A1").Select
  38.             If Cells(2, 1).Value = "" Then
  39.                 fRowB = 1
  40.             Else
  41.                 Selection.End(xlDown).Select
  42.                 fRowB = ActiveCell.Row
  43.             End If
  44.  
  45.             Range("A1 : A" & fRowB).Select
  46.             Selection.Copy
  47.  
  48.  
  49.             Workbooks(fWorkbookName).Activate
  50.  
  51.             Cells(2, 5).Select
  52.             ActiveSheet.Paste
  53.             Cells(2, 5).Select
  54.             Selection.End(xlDown).Select
  55.             fRowB = ActiveCell.Row
  56.  
  57.             Range("H4").Select
  58.             fRow = Cells(4, 8).Value
  59.  
  60.             Cells(fRowNum, 1) = fFileName
  61.             Cells(fRowNum, 2) = fRow
  62.             fRowNum = fRowNum + 1
  63.  
  64.  
  65.  
  66.            Workbooks(fFileName).Activate
  67.            Application.CutCopyMode = False
  68.            Workbooks(fFileName).Close
  69.  
  70.            fFileName = Dir
  71.     Loop
  72.  
  73. End Sub
  74.  
  75.  
Sep 15 '14 #5
twinnyfo
3,653 Expert Mod 2GB
theberner,

Exactly what is not working? Ut does not look like your code would execute flawlessly, but we need to findout wehre and why.

First, I would make a couple recommendations, then a few observations.

First, beginning of your code should look like this:

Expand|Select|Wrap|Line Numbers
  1. Option Compare Text
  2. Option Explicit
  3.  
  4. Sub Checker2()
  5.     Dim fRowNum As Integer
  6.     Dim fColumNum As Integer
  7.     Dim fTRow As Integer
  8.     Dim fWorkbookName As String
  9.     Dim fName As String
  10.     Dim fPathName As String
  11.     Dim fFileName As String
The statement "Option Explicit" ensure that all variables used must be declared. This is a standard VBA coding practice, which can be set by default, and I encourage you to use it always. This is followed by declaring all your variables and declaring the type of variable it is. Again, standard VBA practices.

One particular reason this would be helpful in your case is that you set values for the variables fRowNum, fColumNum and fTRow (all set to 2), yet it appears the only time you refer again to fRowNum is lines 60-62. But, then you efer to fRow and fRowB and it is unclear when, where and why these variables exist.

However, trying to interpret your code, it appears you are working with two different workbooks, trying to copy and paste between the two?

This can be very tricky as sometimes MS Excel has problems disambiguating between the active workbook.

In this case, it is sometimes better to declare a variable of the workbook or worksheet, so that whenever you refer to that variable, the VBA knows exactly which workbook/worksheet you mean. Here is an example:

Expand|Select|Wrap|Line Numbers
  1.     Dim xlApp As Excel.Application
  2.     Dim wbOriginal As Excel.Workbook
  3.     Dim wbNew As Excel.Workbook
  4.     Dim wsOriginal As Excel.Worksheet
  5.     Dim wsNew As Excel.Worksheet
  6.  
  7.     Set xlApp = New Excel.Application
  8.     xlApp.Visible = False
  9.     Set wbOriginal = xlApp.Workbooks.Open("Path\Filename.xlsx")
  10.     Set wbNew = xlApp.Workbooks.Open("Path\Filename2.xlsx")
  11.     Set wsOriginal = wbOriginal.Sheets(1)
  12.     Set wsNew = wbNew.Sheets(1)
  13.     With wsNew
  14.         .Cells(1, 1) = "Test"
  15.     End With
Now, whenever you want to refer to one Worksheet/Workbook or the other, you just use the variable for that particular workbook. There is much flexibility in this method.

If there are particular errors you are receiving, I would be glad to try and work thorugh those with you.

Hope this helps.
Sep 15 '14 #6
Helps alot. bare with me. I last tried to do this in 2008. i think some of the things that worked then are differnet now. But you did help me recall the intent of that version, versus what I am trying to do this time. In that version the task was to list all the file names and then to have the program read that name and search for it in the folder and record the counts. I think i mixed that portion in with this attempt where I was hoping to get the program to read a folder, record the names and counts.

Perhaps I am too rusty to figure this one out.
Sep 16 '14 #7
twinnyfo
3,653 Expert Mod 2GB
My advice for working through a solution would be to start with one file. hard code all the files names and cells as they should be in the excel files. Then, step through the code line by line as it executes, making sure it does what you want it to. Then, when you have mastered the hard coded file, incorporate code that will cycle through the text files.

This may not be the best method, but I often use it when I am either new to a type of procedure or am rusty on its execution. Remember, we are not trying to do a millions things perfectly, we are trying to do one thing perfectly, but doing it a million times. This helps me understand the importance of getting code right the first time, even if there is a littl emore effort involved. In the long run it decreases the headaches of trying to fix bad code.

I am standing by for further assistance if you need it.
Sep 16 '14 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Stein | last post by:
I've seen a couple postings on moving files to folders with set source and destination paths, but I still need a little help taking it a step further. I have a folder with 2,000 Word docs that I...
3
by: MS | last post by:
I would like to be able to examine a folder, and populate a List Box or Combo Box with the files that are in it. How would you go about doing this? The reason is that I would like the user to...
2
by: John Regan | last post by:
Hello All I am trying to find the owner of a file or folder on our network (Windows 2000 Server) using VB.Net and/or API. so I can search for Folders that don't follow our company's specified...
0
by: madhubabumallidi | last post by:
i am designing a web page so that i need to browse a folder and capture all excel file names in that folder, using c#
1
by: =?Utf-8?B?R2VuZXZpZXZlIEQu?= | last post by:
Please help end a debate for me. I have been taught to not use a dot or period within a file name and that the only dot or period should be before the file extension. Is this still the case or...
1
by: mojo123 | last post by:
Hi All, I am looking for a way to count rows in datagrid. The code I have goes something like this: Data1.DatabaseName = Mydata.mdb Data1.Recordsoource = Select * Table1 Where Class = 3 And...
1
by: Ormazd | last post by:
Hello, I was wondering if anyone might be able to help me with a little PERL script? I'm very new and I have been given a task to write a simple Perl script that prints out the file names and...
6
by: angelicdevil | last post by:
how can i get the php to read the all the file names within a folder and put the names into an array?
2
by: Ehsan arman | last post by:
I was wondering how I could read excel file names in a particular folder using Access VBA. I need to compare the file names in that folder with what I have in a field of Access table.
11
NeoPa
by: NeoPa | last post by:
Overview It is often required to prompt the operator of an Access project to select a file or folder. Sure, it's possible to allow them to type it in freehand, or even paste it in from another...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.