473,748 Members | 2,551 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Visual Basic - Looping through files

7 New Member
Hi All

I have created a macro which turns reports done by users into a format that is needed by me. The good this is that all the reports are in the same format.

However my question is around automating this process especially when there could be potentially hundreds of files by users that need converting.

Is there a way a routine could be run automatically which opened all the files on the drive that had been created by users, format them into my format which is a CSV format?

Also I am a little stuck with creating a mastersheet so that when new data comes in I can add this to a master sheet. What happens when it goes over 64000 lines? Can I use a text file?

The code I have written so far is a little rubbish and is below - seeing the files may explain what I am trying to do but I am unable to attach any files to the post :(

any help much appreciated

Thanks

Sub Macro1()

Range("O2").Sel ect
ActiveCell.Form ulaR1C1 = "=RC[-10]+RC[-9]"
Range("P2").Sel ect
ActiveCell.Form ulaR1C1 = "=RC[-7]"
Range("O2").Sel ect
Selection.Copy
Range("E2").Sel ect
Selection.End(x lDown).Select
Selection.End(x lToRight).Selec t
ActiveCell.Offs et(0, 2).Select
Range(Selection , Selection.End(x lUp)).Select
ActiveSheet.Pas te
Range("P2").Sel ect
Application.Cut CopyMode = False
Selection.Copy
Range("E2").Sel ect
Selection.End(x lDown).Select
Selection.End(x lToRight).Selec t
Selection.End(x lToRight).Selec t
ActiveCell.Offs et(0, 1).Select
Range(Selection , Selection.End(x lUp)).Select
ActiveSheet.Pas te
Range("O2:P2"). Select
Range(Selection , Selection.End(x lDown)).Select
Selection.Copy
Application.Cut CopyMode = False
Selection.Copy
Selection.Paste Special Paste:=xlPasteV alues, Operation:=xlNo ne, SkipBlanks _
:=False, Transpose:=Fals e
Sheets.Add
Range("A6").Sel ect
ActiveSheet.Pas te
Range("A5").Sel ect
Application.Cut CopyMode = False
ActiveCell.Form ulaR1C1 = "Times"
Range("B5").Sel ect
ActiveCell.Form ulaR1C1 = "=Sheet1!R[-3]C[1]"
Range("C5").Sel ect
ActiveCell.Form ulaR1C1 = "=Sheet1!R[-3]C[1]"
Range("A2").Sel ect
ActiveCell.Form ulaR1C1 = "Site Name"
Range("B2").Sel ect
ActiveCell.Form ulaR1C1 = "=CONCATENATE(S heet1!RC[-1],""_"",Sheet1!R C)"
Range("A2:C5"). Select
Selection.Copy
Range("A2").Sel ect
Selection.Paste Special Paste:=xlPasteV alues, Operation:=xlNo ne, SkipBlanks _
:=False, Transpose:=Fals e
Application.Cut CopyMode = False
Range("E5").Sel ect
ActiveCell.Form ulaR1C1 = _
"=IF(RC[-3]=""flow"",""02" ",IF(RC[-3]=""pressure""," "01"",IF(RC[-3]=""level percent"",""03" ")))"
ActiveCell.Offs et(2, 0).Select
ActiveCell.Form ulaR1C1 = "=CONCATENA TE(R[-5]C[-3],""_"",R[-2]C)"
ActiveCell.Copy
Range("B2").Sel ect
Selection.Paste Special Paste:=xlPasteV alues, Operation:=xlNo ne, SkipBlanks _
:=False, Transpose:=Fals e
Range("E5").Del ete
Range("E6").Del ete
ActiveSheet.Sel ect
ActiveSheet.Cop y
Range("B2").Sel ect
strName = Range("B2")
ActiveWorkbook. SaveAs Filename:="R:\M aster\" & strName _
, FileFormat:=xlC SV, CreateBackup:=F alse
ActiveWorkbook. Close
ActiveWorkbook. Close
Jan 18 '08 #1
3 2908
kadghar
1,295 Recognized Expert Top Contributor
Hi All
(...)

Is there a way a routine could be run automatically which opened all the files on the drive that had been created by users, format them into my format which is a CSV format? (...)
well, i dont really know how to acces the files' info via VBA, since many useful commands in VB aren't available here. I can only think of using DIR and BuiltinDocument Properties once we've located an excel file (im assuming all this files are excel files). So what im going to do is to create an excel application (as an object). Then im going to run a DIR through all the files in a path and its going to open each excel file. Once its oppened, it's going to check the Author in its properties and if its an author from a list, its going to run Macro1 with it's info (or any other sub, that can actually format them into a csv)

Now, the problem here is that Macro1 is clearly a recorded one. That won't help you, since it takes the info in sheet1 and takes it to sheet2 and do all the work with only one workbook, and worst of all, it uses copy-paste (where you aren't making reference where to copy from and where to paste to) ... but we can certainly discuss that later.

The procedure i've made checks all the files' authors in a single path, i dont think runnig it through the whole HDD would be convinent:

Expand|Select|Wrap|Line Numbers
  1. sub something()
  2. dim Obj1 as object
  3. dim Str1 as string
  4. dim myPath as string
  5. dim i as integer
  6. set obj1 = createobject("excel.application")
  7. mypath = "c:\thepath\" 'please note you should a "\" at the end.
  8. str1 = dir(mypath & "*.xls")
  9. do
  10.     obj1.workbooks.open (mypath & str1)
  11.     for i = 1 to ubound(UsersList)
  12.         if obj1.activeworkbook.builtindocumentproperties("Author").value = userslist(i) then 
  13.             call Macro1 'or do whatever you want with the file
  14.             exit for
  15.         end if
  16.     next
  17.     obj1.activeworkbook.close
  18.     str1 = dir()
  19. Loop Until Str1 = ""
  20. obj1.Visible = True
  21. obj1.Quit
  22. end sub
please note im assuming (once again) that you've created an authors list called UsersList

(...)Also I am a little stuck with creating a mastersheet so that when new data comes in I can add this to a master sheet. What happens when it goes over 64000 lines? Can I use a text file? (...)
You can save it as a textfile, of course, but i'm not getting the point...

Do you want to save the excel book as a text file each time it reaches the limit and start a new one? or do you want to work all the info as a txt file instead of a workbook?


The code I have written so far is a little rubbish and is below - seeing the files may explain what I am trying to do but I am unable to attach any files to the post :(

any help much appreciated

Thanks
yes, i think the code you 'wrote' must be cleaned up a little bit (since you don't really have to close the activeworkbook twice).

To atach files, make the post, then edit it, while editing it you'll see the attaching options.

HTH
Jan 18 '08 #2
richie9648
7 New Member
Thanks HTH - I have attached the files below - yes I agree the code is shocking but I am fairly new to this so any help in cleaning would be good.

Thanks for your comments as well

Rich
Attached Files
File Type: zip vb.zip (67.8 KB, 118 views)
Jan 18 '08 #3
kadghar
1,295 Recognized Expert Top Contributor
Thanks HTH - I have attached the files below - yes I agree the code is shocking but I am fairly new to this so any help in cleaning would be good.

Thanks for your comments as well

Rich
HTH = Hope That Helps;
Call me Kad, i like that nick.

Yes, the macro you recorded has many troubles there. The main one is that you're only refering it to the workbook itself, and if you want to use it for many workbooks, it has to change a little bit. What i recommend you is: first of all you should create a couple of objects, they're going to be Excel Applications:

Excel Application 1 (i'll call it Obj1) will have the User file with 'Original.xls' format

Excel Application 2 (or Obj2) will be the one with Sheet2, but this time im not creating another sheet in Obj1 and then exporting it into another file. Im leaving Obj1 as it is, and working with Obj2.

I will use DIR to check each file *.xls in some path (you write it), for each file, its going to:

1. open the file in Obj1
2. check if its "author" its in the list
3. if its in the list, it'll call Macro1Bis (by me, yeah)
4. close the workbook (but not the application)

** Please note Step 2 is commented in the code and will not do it, it will run Macro1Bis for each and every XLS file in the path. Later we can discus how to work with that UserList.

Macro1Bis does exactly what your macro used to do, but without Copy-Paste, and istead of Sheet1 uses Obj1.ActiveWork book.ActiveShee t and instead of Sheet2 uses Obj2.ActiveWork book.ActiveShee t. And finaly, instead of saving Obj2 as an XLS file, it saves a CSV... nice ^.^

Please note: Macro1Bis has exactly the same bug your Macro1 used to have. it uses END(xldown) and END(xlright) i dont like using excel's constants so i use -4121 instead of xldown and -4161 instead of xlright, anyway, it's the same thing. The problem is:

END(xldown) its like pressing Ctrl + DownArrow while in the excel worksheet
if you're standing in cell E2 and you only have that observation, and press Ctrl+DownArrow, it'll send you to the end of the file, to the very last row, then if you want to make an offset..oops, there're no cells left to move to. you're in the end of the worksheet.
This of course will not happen when you have at least 2 observations, since it'll move to the last one, and you'll have the range you want =)

So: THIS CODE IS USELES IF YOU HAVE ONLY ONE OBSERVATION.

well, that's all I have to say, paste it into a new module, run the RunMe sub, but before, fill the blanks in Line 10, and check that you have an unit R:\ (line 56), because i didnt and it caused me some troubles =(. (if not, just chage it to C:\, not big deal)

HTH

(oh, and thanks, i had some free time and i like spending it doing some coding)

Expand|Select|Wrap|Line Numbers
  1. Dim Obj1 As Object
  2. Dim Obj2 As Object
  3. Dim UserList()
  4. Sub RunMe()
  5. Dim Str1 As String
  6. Dim myPath As String
  7. Dim i As Integer
  8. Set Obj1 = CreateObject("excel.application")
  9.  
  10. myPath = "C:\[WriteHereThePath]\" 'please note you should a "\" at the end.
  11.  
  12. Str1 = Dir(myPath & "*.xls")
  13. Set Obj2 = CreateObject("excel.application")
  14. Do
  15.     Obj1.Application.DisplayAlerts = False
  16.     Obj1.Workbooks.Open (myPath & Str1)
  17.     'For i = 1 To UBound(userslist)
  18.         'If Obj1.ActiveWorkbook.BuiltinDocumentProperties("Author").Value = userslist(i) Then
  19.              Call Macro1Bis 'or do whatever you want with the file
  20.         '    Exit For
  21.         'End If
  22.     'Next
  23.     Obj1.ActiveWorkbook.Close
  24.     Obj1.Application.DisplayAlerts = True
  25.     Str1 = Dir()
  26. Loop Until Str1 = ""
  27. Set Obj1 = Nothing
  28. Set Obj2 = Nothing
  29. End Sub
  30. Sub Macro1Bis()
  31.     'Not a recorded Macro, created by Kad
  32.     'Dont run me, as you can see RunMe will call me in time
  33.     Dim a
  34.     Dim Str1 As String
  35.     Dim Str2 As String
  36.     With Obj1.ActiveWorkbook.ActiveSheet
  37.         .Range(.Cells(2, 15), .Cells(2, 5).End(-4121).End(-4161).Offset(0, 2)).FormulaR1C1 = "=RC[-10]+RC[-9]"
  38.         .Range(.Cells(2, 15), .Cells(2, 15).End(-4121).Offset(0, 1)).FormulaR1C1 = "=RC[-7]"
  39.         a = .Range(.Cells(2, 15), .Cells(2, 16).End(-4121))
  40.     End With
  41.     Obj2.Workbooks.Add
  42.     With Obj2.ActiveWorkbook.ActiveSheet
  43.         .Range(.Cells(6, 1), .Cells(5 + UBound(a), UBound(a, 2))) = a
  44.         .Cells(5, 1) = "Times"
  45.         .Cells(5, 2) = Obj1.ActiveWorkbook.ActiveSheet.Cells(2, 3)
  46.         Select Case UCase(.Cells(5, 2))
  47.             Case "PRESSURE": Str1 = "01"
  48.             Case "FLOW": Str1 = "02"
  49.             Case "LEVEL": Str1 = "03"
  50.         End Select
  51.         .Cells(5, 3) = Obj1.ActiveWorkbook.ActiveSheet.Cells(2, 4)
  52.         .Cells(2, 1) = "Site Name"
  53.         .Cells(2, 2) = Obj1.ActiveWorkbook.ActiveSheet.Cells(2, 1) & "_" & Obj1.ActiveWorkbook.ActiveSheet.Cells(2, 2) & "_" & Str1
  54.          Str2 = .Cells(2, 2)
  55.          Obj2.Application.DisplayAlerts = False
  56.          Obj2.ActiveWorkbook.SaveAs Filename:="r:\" & Str2, FileFormat:=xlCSV, CreateBackup:=False
  57.     End With
  58.     Obj2.ActiveWorkbook.Close
  59.     Obj2.Application.DisplayAlerts = True
  60. End Sub
Jan 19 '08 #4

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

Similar topics

2
3602
by: Ralph | last post by:
I used to have Visual Basic .net std. 2003 installed on WinXP SP1A. But I found it too hard to upgrade WinXP to SP2. Now, I do have WinXP SP2 installed, but I am having problems installing Visual Basic .net standard 2003. Not installing Visual Basic at the WinXP SP1A level - was the only way I found that I could install WinXPSP2. My computer was purchased with WinXP SP1 Professional. I also have Norton Internet Security and Norton...
26
10872
by: Bruno Jouhier [MVP] | last post by:
I'm currently experiencing a strange phenomenon: At my Office, Visual Studio takes a very long time to compile our solution (more than 1 minute for the first project). At home, Visual Studio compiles the same solution much faster (about 10 seconds for the first project). My home computer is only marginally faster than the one I have at the office (P4 2.53 vs. P4 2.4, same amount of RAM). On the slow machine, the CPU usage is very low,...
4
1949
by: LCAdeveloper | last post by:
I have had to move to Visual Studio.NET Pro. from Visual Basic 4.0 and am now starting to re-write our code. I was a bit surprised to find that Visual Basic.NET no longer supports fixed length strings, which is a pain as we use our own database format with specific, user-defined data types and random access files. An example module content would be Option Explici Type Record Operation As String * 4 unit As String * 2 Marker1 As String *...
16
1451
by: Jesse Liberty | last post by:
I am writing a new book on Visual Basic 2005, targeted at VB6 programmers, and to some degree VB.NET 1.x programmers. I'd like to sign up a (limited) number of volunteers to read the book and provide feedback. To participate you would... 1. Sign a non-disclosure agreement 2. Read each chapter in Word format and mark it up and return it within a week of receipt 3. Be open honest and direct, providing feedback about the content and...
7
1861
by: gerryLowry::Ability Business Computer Services {KC | last post by:
"Getting Back Your Visual Basic 6.0 Goodies" by Billy Hollis, 2003-5-14, states: "Getting a Forms Collection Visual Basic 6.0 developers are often fond of looping through the currently loaded forms in an application to find out something, such as if a particular form it loaded, or how many of a particular type of form are loaded. Windows Forms does not include a Forms collection, however, so gaining such functionality in Visual Basic...
6
11608
by: JimmyKoolPantz | last post by:
I have been given the task of converting a program from VFP (visual foxpro) to Visual Basic.net. My question is "Is it possible to generate a DBF file Dynamically(at runtime) using Visual Basic.Net?" With all the field properties, such as, field length and type. I'm not sure if this is a stupid quesiton or If I am just over looking something, but I have not found solid information on the internet about this topic. Any useful...
6
2532
by: Salman | last post by:
I would like to know how I can distribute the application that I create with Visual C++ express edition. I checked the menu options to find a deploy option similar to the one found on the Visual Basic Express Edition but could not find one. I have even searched the help files and could not find anything useful for me. I want to simply package my application so that I may install it on another computer.
20
2850
by: Ifoel | last post by:
Hi all, Sorry im beginer in vb. I want making programm looping character or number. Just say i have numbers from 100 to 10000. just sample: Private Sub Timer1_Timer() if check1.value= 1 then
0
7334
jwwicks
by: jwwicks | last post by:
Introduction This tutorial describes how to use Visual Studio to create a new C++ program, compile/run a program, resume work on an existing program and debug a program. It is aimed at the beginning CIS student who is struggling to get their programs working. I work in the computer lab at the college I'm attending and I see many students who don't know how to use the IDE for best results. Visual Studio automatically creates a number of...
0
8831
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9555
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9376
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9250
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4607
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4878
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3315
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.