I'm trying to write a LS agent to scan a directory in windows eg:'C:\' for any files and sub-directories. For each sub-directory, it will go inside and search for more files and sub-directories and continues until there's no more to look for. I'm used to write recursive code to replace or remove characters in a long string but for this one I'm totally lost. Below is my code (it's a mix of code from the domino help file and one I found in IBM site):
Sub Initialize
Dim pathname As String, filename As String
pathname = "C:\*.*"
filename = Dir(pathname, 16)
Print "Begin scan"
Do While filename<>""
If IsDir(pathname+filename)=True Then
Print pathname+filename+" is a directory"
'look for more directories and files in here
Else
Print filename+" is a file"
End If
filename=Dir()
Loop
Print "Finish scan"
End Sub
Function IsDir(Path As String) As Integer
Dim Void&
Dim Result As Boolean
On Error GoTo ErrorHandler
Void=FileLen(Path)
Result=False
GoTo Over
ErrorHandler:
Result=True
Resume Over
Over:
IsDir=Result
End Function
What do I need to change to make the code recursive at the commented part? ('look for more directories and files in here). I'm not just trying to find a specific file or directory. I want all that's available withing one. If I'm able to do that, then I can retrieve them and save into a NotesDocument.
I've used this solution a couple of times and it works a treat:
First of all, you don't want to call Initialize recursively. You need a function that you're passing a pathname into.
Secondly, because of the stateful way that the DIR function works, I think you have to do this with two loops. In the first loop, you process your regular files and you put the folder names ino a list. Then in the second loop, you go through the list of folders and call the recursive function passing in the path to each one.
Related
So I'm fairly new to VBA, using it within some spreadsheets so forgive me if this is a super obvious fix, I'm sure it is but have spent hours on with with no success.
The following piece of code will lie inside of an if statement - not sure if thats worth mentioning or not.
I want to simply move, and rename files from one location to the other
It needs to utilize cmd.exe, and use the 'move' argument - the source path and source destinations will be changeable depending on the pc - so it will need to use the '%temp% - as the initial file will be stored in this folder, and %userprofile% for the destination path.
Here is the code so far - I think the issue is just to do with the formatting -
Sub movefile ()
Dim Origpath As String
Dim NewPath As String
OrigPath="%temp%\newfile.txt"
NewPath="%userprofile%`Documents\newfile.vbs"
<<next code inside of an if statement>>
moveFile="C:\windows\system32\cmd.exe /C move " & OrigPath & " " & NewPath
End Sub
Maybe the " and & arent placed correctly? But the code works fine up until the line 'movefile...'
Probably a super easy way of doing it - help please!!
Try using Name:
name OrigPath as NewPath
Alternatively you can use use fdo movefile, as explained in this answer.
This is my first time using such forum.
I have exactly the same question as here:
How to release an object and clear memory in VBA
In this thread, the question was unfortunately not solved...
With Excel VBA I connect to another program (namely Aspen EDR). For that purpose I have an according Add-In installed. To access Aspen EDR I need to add an object. After I'm done I want to release the object to save some memory. First thing I tried is this:
Dim ObjEDR As BJACApp
Dim Path As String
Path = 'assume this is the correct path to the file i want to open
Set ObjEDR = New BJACApp ' Create the BJAC object
If Not ObjEDR.FileOpen(Path) Then
MsgBox "Can't open file!"
End If
'...
Set ObjEDR = Nothing
After I set the object nothing, Excel does not release the memory (as I can see in my task manager). Of course after a few hundred iterations (I have to open a lot of these files) I get an error message, that Excel is out of memory. I read a few threads and apparently nothing only deletes some kind of reference to the object but not the object itself, so I tried adding fileclose
'...
ObjEDR.FileClose
Set ObjEDR = Nothing
When executing the FileClose I can see that a little memory is released (0.5 of 3MB) but still there is a lot of memory accumulating.
Also when not using the "Now" it is not working and I get "runtime error'424': Object required" when executing Set ObjEDR = BJACApp
I also read about "pointers" that might cause the staying memory increase, but how can I find and clear/delete them?
Does anyone has an idea?
I would really appreciate it!
If .Quit (or the object's equivalent) and setting the object to Nothing is not working for you, then you could try relying on VBA's garbage collector to do the job.
Essentially what this means is that you would need to split the sub in two, have the main sub, and within that sub call the sub that will open and close your object. Hopefully, upon the second sub exiting, VBA will clean up those objects.
Sub Main()
Dim filePath As String
For Each [..] In [..] ' Or use a Do...Loop
filePath = 'assume this is the correct path to the file i want to open
openObj filePath 'call the sub below
Next [..]
End Sub
Sub openObj(ByVal Path As String)
Dim ObjEDR As BJACApp
Set ObjEDR = New BJACApp ' Create the BJAC object
If Not ObjEDR.FileOpen(Path) Then
MsgBox "Can't open file!"
End If
[...] 'your code to perform the needed actions with your obj
ObjEDR.FileClose
Set ObjEDR = Nothing
End Sub
I don't know anything about this object, but you should also try .Quit and .Close
Another method is to not create a new object for each path. Place the Set ObjEDR on the outside of your loop, and utilize the same object every time you open the new file.
Ok, to those who are interested:
The support of Aspen Tech told me that
ObjEDR.dispose()
should work, but just for versions above V8.4.
So this did not solved my problem and I built a workaround using MATLAB which opens and closes Excel after each run. So I loose time opening and closing the Excel file, but the memory of excel is not increasing until it stops working.
I have directory full of .txt files (2000 files). they have very long name. I want to edit their name and just keep certain letter from inside of their name as file name.
like this :
UNCID_279113.TCGA-A6-2683-01A-01R-0821-07.100902_UNC7-RDR3001641_00025_FC_62EPOAAXX.1.trimmed.annotated.gene.quantification.txt
I want eliminate this long names and just keep the name starting from TCGA and ending after three - ; for example, my new file name would be : TCGA-A6-2683-01A
does anybody knows how can I do this for whole files in one directory?
Assuming the files are in the current directory:
library(gsubfn)
pat <- "TCGA-[^-]*-[^-]*-[^-]*"
file.names <- dir(pattern = pat)
new.names <- strapplyc(file.names, pat, simplify = TRUE)
file.rename(file.names, new.names)
Create a shell/batch script Here is a variation. It produces a UNIX shell file or a Windows batch file. You can then review the file and run it:
# UNIX
writeLines(paste("mv", file.names, new.names), con = "tcga_rename.sh")
shell("tcga_rename.sh")
or on Windows:
# Windows
writeLines(paste("rename", file.names, new.names), con = "tcga_rename.bat")
shell("tcga_rename.bat")
REVISED: Factored out pat, simplified and added variations.
Assuming your files are in the current working directory, try
library(stringr)
files <- list.files(".", pattern=".txt")
file.rename(files, str_extract(files, "TCGA(-\\w+){3}"))
You can do something like this:
pattern <- ".*(TCGA-[^-]+-[^-]+-[^-]*).*"
file.rename(
list.files("."),
sub(pattern, "\\1", list.files("."))
)
But be super careful that the sub command does what you think it will do before you run the full thing (i.e. just run the sub piece). Hard to be sure this won't cause a problem without knowing what patterns you have in your file names.
Also, in this case replace list.files(".") with your directory. Note you don't need to filter our the files that match the pattern in the first place since sub will only modify the file names that do match the pattern (not super efficient if you have a lot of files that don't match the pattern, but easier to write, if a concern, you can use the pattern argument as Greg Snow does).
You cane use list.files() to get a list of the filenames in the directory, then use substitute with regular expressions to edit the names, then file.rename to actually do the renaming.
Something like (untested):
curfiles <- list.files(pattern='TCGA') # only grab files with TCGA in them
newfiles <- sub("^.*(TCGA-[a-zA-z0-9]+-[a-zA-Z0-9]+-[a-zA-Z0-9]+).*$", "\\1", curfiles)
file.rename(curfiles,newfiles)
i am using mergext dropboxsync to synchronise my data from the ipad.
my question is.
how we get the file from the special folder specialfolderpath
and how we check if the file exist into the dropbox.
i am no using fields for folder or the files i want the procedure to be hidden from the user
to get my folder and path i use the simple bellow code.
put specialfolderpath("documents") & "/myfile.sqlite" into myPath
and here is the code from the button i use
on mouseUp
goToParent --<command
repeat for each line tempitem in fld "sFolders" --<hide field
add 1 to t
if tempitem ="hairaid-backup" then
put 1 into fExist
end if
end repeat
--!! if folder exist
if fExist is a number then
else
try
mergDropboxCreateFolder (hairaid &"-"&backup)
catch e
answer e
end try
end if
end mouseUp
I would not really recommend synchronising a sqlite database over dropbox. You are likely to have better results creating a tree for files for dropbox to sync as one large file is likely to end up with conflicted versions.
However, answering your question in the general sense you would need to do something like this:
put url ("binfile:"&myPath) into myData
mergDropboxWriteFile relativePath,myData
Then to get the data you:
put merDropboxGetFile(relativePath) into myData
I'm working on writing a Windows batch file that is called by a Java program. A number of different strings denoting file directories are passed into the batch file as parameters. I am trying to figure out how to extract a string after the last instance of the "\". For example, I have three directories:
C:\Users\owner\Documents
C:\Users\owner\Videos
C:\Users\owner\Pictures\Trip
I would like to split it so that the strings become:
Documents
Videos
Trip
How would you guys suggest I do this?
EDIT: A follow-up question has been asked here: For loop in Windows batch file: Error: "The syntax of the command is incorrect"
After assigned one parameter to "param" variable, use:
for %%a in (%param:\= %) do set lastDir=%%a
This method works as long as the last directory does NOT have spaces. This detail may be fixed, if needed. The processing of all parameters would be like this:
:nextParam
set "param=%~1"
if not defined param goto endParams
for %%a in (%param:\= %) do set lastDir=%%a
echo Last dir: %lastDir%
shift
goto nextParam
:endParams
Or, in a simpler way (with no spaces restrictions):
:nextParam
if "%~1" equ "" goto endParams
echo Last dir: %~N1
shift
goto nextParam
:endParams
If the strings are passed as arguments 1-3. you can use %~n1, %~n2, %~n3 to get the last folder in the path.