I'm having a set of files which I want to loop through with the filenames: Budget 2015, Budget 2016, Budget 2017 up to 2022. I loop through them using Dir.
Dim OpenWb as workbook
path = Dir("C:\pathtofile\Budget 20??.xlsx") 'Using the ? Dir Wildcard
filepath = "C:\pathtofile\" 'Since Dir returns file name, not the whole path
myHeadings = Split("Januari,Februari,Mars,April,Maj,Juni,Juli,Augusti,September,Oktober,November,December", ",")
j = 0
Do While Len(path) > 0
i = 0
If Dir = "Budget 2014.xlsx" Then
j=0
Else
For i = 0 To UBound(myHeadings)
Set openWb = Workbooks.Open(filepath & path)
MsgBox Len(path)
Set openWs = openWb.Sheets(myHeadings(i))
If openWs.Range("C34") = 0 Then
currentWb.Sheets("Indata").Cells(70, i + 27 + 12 * (j + 1)).Value = ""
Else
currentWb.Sheets("Indata").Cells(70, i + 27 + 12 * (j + 1)).Value = openWs.Range("C34")
End If
Next i
End if
path = Dir
j= j + 1
Loop
The trouble is that in the filepath there's also a file called Budget 2014, which I do not want to loop through because 1) It's not necessary, the values are computed already and 2) Since it screws up my indices in the loop
Updated my code. But using msgBox (path) inside the for i = 0... loop returns "Budget 2014.xlsx" which I did not want to loop, and hence this "messes" with my j subscript.
You could make use of the Year method. Something like,
Dim OpenWb as workbook, yearNo As Long, filepath As String
filepath = "C:\pathtofile\"
yearNo = Year(Date())
path = Dir("C:\pathtofile\Budget " & yearNo & ".xlsx")
Do While Len(path) > 0
set OpenWb = Workbooks.open(filepath & path) ' Since Dir only returns file name
'Doing some things
yearNo = yearNo + 1
path = Dir("C:\pathtofile\Budget " & yearNo & ".xlsx")
Loop
You could also try this:
Dim OpenWb as workbook
path = Dir("C:\pathtofile\Budget 20??.xlsx") 'Using the ? Dir Wildcard
filepath = "C:\pathtofile\" 'Since Dir returns file name, not the whole path
myHeadings = Split("Januari,Februari,Mars,April,Maj,Juni,Juli,Augusti,September,Oktober,November,December", ",")
j = 0
Do While Len(path) > 0
i = 0
'change here: only execute if it's NOT the file you're NOT after
If Dir <> "Budget 2014.xlsx" Then
For i = 0 To UBound(myHeadings)
Set openWb = Workbooks.Open(filepath & path)
MsgBox Len(path)
Set openWs = openWb.Sheets(myHeadings(i))
If openWs.Range("C34") = 0 Then
currentWb.Sheets("Indata").Cells(70, i + 27 + 12 * (j + 1)).Value = ""
Else
currentWb.Sheets("Indata").Cells(70, i + 27 + 12 * (j + 1)).Value = openWs.Range("C34")
End If
Next i
'Change here: only update path & j if you processed the file
path = Dir
j= j + 1
End if
Loop
Sub M_snb()
c00 = "C:\pathtofile\"
sn = Application.GetCustomListContents(4)
c01 = Dir(c00 & "Budget 20*.xlsx")
Do While c01 <> ""
If c01 <> "Budget 2014.xlsx" Then
With GetObject(c00 & c01)
For j = 0 To UBound(sn)
c02 = c02 & "|" & IIf(.Sheets(sn(j)).Range("C34") = 0, "", .Sheets(sn(j)).Range("C34"))
Next
.Close 0
End With
End If
c01 = Dir
Loop
sp = Split(Mid(c02, 2), "|")
ThisWorkbook.Sheets("Indata").Cells(70, 51).Resize(, UBound(sp)) = sp
End Sub
Related
I hope some of you can help with the code under these text, I can export Attachments which are in the body of an Lotus Notes Mail, but also I need to export them, when they aren't in the body (like "normal" attachments).
Set LNItem = doc.GETFIRSTITEM("Body")
If doc.HasEmbedded Then
int_Anhang = 1
x = 0
Worksheets("Mails").Cells(j, 3).Value = 0
On Error Resume Next
For Each LNAttachment In LNItem.EmbeddedObjects
y = 0
AttPath = ActiveWorkbook.path & "1-Weiterleitung_Mail-Anhang" & y & "-" + LNAttachment.Name
While Dir(AttPath) <> ""
y = y + 1
AttPath = ActiveWorkbook.path & "1-Weiterleitung_Mail-Anhang" & y & "-" + LNAttachment.Name
Wend
LNAttachment.ExtractFile (AttPath)
Worksheets("Mails").Cells(j, 3).Value = Worksheets("Mails").Cells(j, 3).Value + 1
Worksheets("Mails").Cells(j, 7 + x).Value = y & "-" + LNAttachment.Name
x = x + 1
Next
On Error GoTo Fehler
Debug.Print vbNewLine
End If
Can someone help?
My Question in other communities:
ms-office-forum.net
Herber.de
Here are more code:
Dim sess As Object, db As Object, folder As Object, dc As Object, docMemo As Object, docNext As Object, LNItem As Object
Dim memoSenders As Variant, memoAnhang As Variant, memoInhalt As Variant, memoLayout As Variant, LNAttachment As Variant
Dim memoDate As Date, todayDate As Date
Dim mail_Server As String, mail_Datei As String, memoSubject As String, AttPath As String
Dim y As Integer, int_test As Integer
'On Error GoTo Fehler_Notes
On Error GoTo Fehler
Set sess = CreateObject("Notes.NotesSession")
'sess.Initialize ("")
'On Error GoTo Fehler
mail_Server = Worksheets("Daten").Cells(2, 2).Value
mail_Datei = Worksheets("Daten").Cells(2, 3).Value
'Open the mail database in notes
Set db = sess.GetDatabase(mail_Server, mail_Datei)
If db.IsOpen = True Then
'Already open for mail
Else
db.OPENMAIL
End If
int_test = 0
Do While Worksheets("Daten").Cells(i, 6).Value <> ""
Set folder = db.GetView(Worksheets("Daten").Cells(i, 6).Value)
If Worksheets("Daten").Cells(i, 9).Value <> "" Then
todayDate = Worksheets("Daten").Cells(i, 9).Value
Else
Worksheets("Daten").Cells(i, 9).Value = "01.01.2000 00:00"
todayDate = Worksheets("Daten").Cells(i, 9).Value
End If
Set doc = folder.GetFirstDocument
Do Until doc Is Nothing
Set docNext = folder.GetNextDocument(doc)
'Datum des Empfangs
Worksheets("Daten").Cells(29, 2).Value = doc.GetItemValue("DeliveredDate")
memoDate = Worksheets("Daten").Cells(29, 2).Value
int_test = int_test + 1
int_xxx = int_xxx + 1
memoSenders = doc.GetItemValue("From")
memoInhalt = doc.GetItemValue("Body")
memoLayout = doc.GetItemValue("Form")
memoSubject = doc.GetItemValue("Subject")(0)
Worksheets("Mails").Cells(j, 1).Value = i - 2
Worksheets("Mails").Cells(j, 2).Value = memoSenders
Worksheets("Mails").Cells(j, 4).Value = memoInhalt
Worksheets("Mails").Cells(j, 5).Value = memoLayout
Worksheets("Mails").Cells(j, 6).Value = memoSubject
'Prüfen ob Attachments innerhalb der Mail vorhanden sind
Set LNItem = doc.GETFIRSTITEM("Body")
If doc.HasEmbedded Then
int_Anhang = 1
x = 0
Worksheets("Mails").Cells(j, 3).Value = 0
On Error Resume Next
For Each LNAttachment In doc.EmbeddedObjects
y = 0
AttPath = ActiveWorkbook.path & "\01-Weiterleitung_Mail-Anhang\" & y & "-" + LNAttachment.Name
While Dir(AttPath) <> ""
y = y + 1
AttPath = ActiveWorkbook.path & "\01-Weiterleitung_Mail-Anhang\" & y & "-" + LNAttachment.Name
Wend
LNAttachment.ExtractFile (AttPath)
Worksheets("Mails").Cells(j, 3).Value = Worksheets("Mails").Cells(j, 3).Value + 1
Worksheets("Mails").Cells(j, 7 + x).Value = y & "-" + LNAttachment.Name
x = x + 1
Next
On Error GoTo Fehler
Debug.Print vbNewLine
End If
Call doc.PutInFolder(Worksheets("Daten").Cells(6, 3).Value)
Call doc.MarkRead
Call doc.RemoveFromFolder(Worksheets("Daten").Cells(i, 6).Value)
j = j + 1
Set doc = docNext
Loop
Worksheets("Daten").Cells(i, 9).Value = CStr(Format(Now, "MM/DD/YYYY hh:mm"))
i = i + 1
Loop
If int_test <> 0 Then
i = 3
ReadNotesEmail i, j
End If
int_error = 0
Exit Sub
Regards
NotesDocument has also a property EmbeddedObjects.
You can use it this way:
For Each LNAttachment In doc.EmbeddedObjects
...
Next
I've try to make the code from Duston work in Excel VBA:
Set Item = Doc.GetFirstItem("$file")
If LCase(Item.Name) = "$file" Then
Set FileItem = Item
FileName = FileItem.Values(0)
Set Object = Doc.GetAttachment(FileName)
AttPath = ActiveWorkbook.path & "\01-Weiterleitung_Mail-Anhang\" & "1" & "-"
' extract the file ..
Call Object.ExtractFile(AttPath & FileName)
End If
My code produce no error and the script goes into the If-Case, but nothing happens. (The "Filename" is empty)
check for File name and you can get the embededobject
this is the java code:
String path="";
Vector fileName= session.evaluate("#AttachmentNames", document);
for (int i = 0; i < fileName.size(); i++) {
EmbeddedObject embeddedObject =
document.getAttachment(fileName.get(i));
embeddedObject .extractFile(path+fileName.get(i));
}
Also check for items named $File. Some sample code is located in this link:
http://www.richardcivil.net/archives/157
In particular:
If Lcase( item.Name ) = "$file" Then
' get the filename ...
Set FileItem = Item
FileName = FileItem.Values(0)
Set Object = sourceDoc.GetAttachment( FileName )
' extract the file ..
Call object.ExtractFile( tempDir & FileName )
' upload the file ..
Set newObject = attachmentBody.EmbedObject( object.Type, "", tempDir & FileName )
' kill the file ..
Kill tempDir & FileName
End If
I am totally new to VBA, looking for tips or hints to solve this question.
I am trying to loop through all the files in a folder and trying to split the filename into three parts that are separated by underscore and then paste those into a spreadsheet. After that, pivot it and count how many files there are in a new sheet.
For example, Filename : CA_File_20170810.txt
So it looks like this:
**IPA TYPE DATE Filename Filepath**
CA File 20170810
*IPA, Type, Date,filename, filepath are columns headers in excel.
Here is what I have in my code so far
Sub LoopingThroughFiles()
Dim f As String
Dim G As String
Dim File As Variant
Dim MyObj As Object
Dim MySource As Object
Dim FileName As Variant
Dim TypeName As Variant
Cells(1, 1) = "IPA"
Cells(1, 2) = "TYPE"
Cells(1, 3) = "DATE"
Cells(1, 4) = "FILENAME"
Cells(1, 5) = "FILEPATH"
Cells(2, 1).Select
f = Dir("C:\Users\kxc8574\Documents\VBA_Practice\")
G = Dir("C:\Users\kxc8574\Documents\VBA_Practice\")
If Right(f, 1) <> "\" Then
f = f + "\"
Cells(2, 1).Select
Do While Len(f) > 0
IpaName = Left(f, InStr(f, "_") - 1)
ActiveCell.Formula = IpaName
ActiveCell.Offset(1, 0).Select
f = Dir()
Loop
Do While Len(G) > 0
TypeName = Mid(G, InStr(G, "_") + 1, InStr(G, "File_") - InStr(G, "_") - 1)
ActiveCell.Formula = TypeName
ActiveCell.Offset(1, 0).Select
G = Dir()
Loop
End If
End Sub
I am missing a lot of things, not sure how to really continue. This code gives me an error "invalid procedure call" when it reaches the G = Dir()
Thanks for your help !!!
First, paste the text under "Explanation" into A1 of a worksheet. Then paste the code under "Code" into a module. Make sure the workbook is in the same directory as your .txt files. Then, run the macro. See animated gif for the result.
"Explanation"
This workbook contains a macro which will
1) Make a new sheet in this workbook named "Combined"
2) Open a copy of each .txt file located in the same directory as this workbook
3) extract the text between "_" characters
4) place the separated text into columns
5) count the number of .txt files processed
Note: Any sheet named "Combined" in this Workbook will be deleted
"Code"
Option Explicit
Sub CombineFiles()
Dim theDir As String, theFile As String
Dim sh As Worksheet, wk As Workbook, newSheet As Worksheet
Dim r As Range, parts() As String
Dim i As Long, s As String
Dim Done As Boolean, numFiles As Integer
Const ext = ".txt"
Err.Clear
theDir = ThisWorkbook.Path
'explain what program does
Worksheets("Program").Select
For i = 1 To 7
s = s & Cells(i, 1) & vbCr & vbCr
Next i
s = s & vbCr
s = MsgBox(s, vbYesNoCancel, "What this macro does")
If s <> vbYes Then End
For Each sh In Worksheets
If sh.Name = "Combined" Then
Application.DisplayAlerts = False
sh.Delete
Application.DisplayAlerts = True
End If
Next
Set newSheet = ThisWorkbook.Sheets.Add
newSheet.Name = "Combined"
'Loop through all files in directory with ext
s = Dir(theDir & "\*" & ext)
Set r = Range("A1")
r = "IPA"
r.Offset(0, 1) = "Type"
r.Offset(0, 2) = "Date"
r.Offset(0, 3) = "filename"
r.Offset(0, 4) = "filepath"
While s <> ""
numFiles = numFiles + 1
parts = Split(s, "_")
Set r = r.Offset(1, 0)
For i = 0 To 2
r.Offset(, i) = Replace(parts(i), ".txt", "")
Next i
r.Offset(, 3) = s
r.Offset(, 4) = theDir & "\" & s & ext
s = Dir()
Wend
MsgBox (numFiles & " files were processed.")
End Sub
Untested but should give you some idea:
Sub LoopingThroughFiles()
Const FPATH As String = "C:\Users\kxc8574\Documents\VBA_Practice\"
Dim f As String, i As Long, arr, sht As Worksheet
Set sht = ActiveSheet
sht.Cells(1, 1).Resize(1, 5).Value = _
Array("IPA", "TYPE", "DATE", "FILENAME", "FILEPATH")
f = Dir(FPATH & "*.txt") '<< only txt files
i = 2
Do While f <> ""
'split filename on underscore after replacing the ".txt"
arr = Split(Replace(f, ".txt", ""), "_", 3)
sht.Cells(i, 1).Resize(1, UBound(arr) + 1).Value = arr
sht.Cells(i, 4).Value = f
sht.Cells(i, 5).Value = FPATH
f = Dir() '<< next file
i = i + 1
Loop
End Sub
Untested but perhaps something like this??
Sub HashFiles()
Dim MyDir As String, MyIPA As Variant, MyType As Variant, MyDate As Variant, i As Integer, oFile As Object, oFSO As Object, oFolder As Object, oFiles As Object
MyDir = "C:\Users\kxc8574\Documents\VBA_Practice\"
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(MyDir)
Set oFiles = oFolder.Files
ReDim MyIPA(1 To oFiles.Count)
ReDim MyType(1 To oFiles.Count)
ReDim MyDate(1 To oFiles.Count)
i = 1
For Each oFile In oFiles
MyIPA(i) = Split(oFile.Name, "_")(0)
MyType(i) = Split(oFile.Name, "_")(1)
MyDate(i) = Split(oFile.Name, "_")(2)
i = i + 1
Next
Range("A2").Resize(UBound(MyIPA) + 1, 1) = Application.Transpose(MyIPA)
Range("B2").Resize(UBound(MyType) + 1, 1) = Application.Transpose(MyType)
Range("C2").Resize(UBound(MyDate) + 1, 1) = Application.Transpose(MyDate)
End Sub
So I did a very simple loop VBA to consolidate data from different workbook into single workbook. I got the out of range error keep promting me and I've tried my best to think but it's a dead end for me. Appreciate if can get some input from the seniors.
Sub consolidate()
Application.ScreenUpdating = False
Set mb = ThisWorkbook
myfdr = ThisWorkbook.Path
fname = Dir(myfdr & "\*.csv")
Do Until fname = Empty
If fname <> mb.Name Then
Set wb = Workbooks.Open(myfdr & "\" & fname)
mg = Range("A1").End(xlDown).Row
Range("M4").Value = mg
wb.Worksheets.Copy After:=mb.Sheets(mb.Sheets.Count)
wb.Close SaveChanges:=False
n = n + 1
End If
fname = Dir
Loop
Application.ScreenUpdating = True
MsgBox n & "Done"
End Sub
Sub Union()
Application.ScreenUpdating = False
Set ms = Worksheets("Sheet1")
fsn = 1
k = 0
Set mb = ThisWorkbook
myfdr = ThisWorkbook.Path
fname = Dir(myfdr & "\*.csv")
Do Until fname = Empty
If fname <> mb.Name Then
sn = Mid(fname, 1, Len(fname) - 4)
Set cs = Worksheets(sn) '<<<<The subscript out of range error happened here
If fsn = 1 Then
fsn = 0
For g = 1 To cs.Cells(4, 13)
k = k + 1
For r = 1 To 10
ms.Cells(k, r) = cs.Cells(g, r)
Next r
Next g
Else
For g = 9 To cs.Cells(4, 13)
k = k + 1
For r = 1 To 10
ms.Cells(k, r) = cs.Cells(g, r)
Next r
Next g
End If
End If
fname = Dir
Loop
End Sub
i am working on this code below
i try to get data from another workbooks sheet1
my problem is there are two ” Financial Depth” with different value in workbook sheet1
how i can get them two different cell
example
Financial Depth=10.000
Financial Depth=24.000
this code get first value .(Financial Depth=10.000)......
Sub Balance()
Dim I As Integer
Dim myfile As String
Pathname = “E:\test\”
I = 1
myfile = Dir(Pathname & “*.xls”)
Cells(1, I) = myfile
StartingPoint:
I = I + 1
myfile = Dir
Cells(I, 1) = myfile
If myfile “” Then GoTo StartingPoint
I = I – 1
For K = 1 To I
‘On Error Resume Next
‘ *** workbook name***
Filename = Cells(K, 1)
Workbooks.Open (Pathname & Filename)
‘ *** company name ***
Cells(K, 2) = Workbooks(Filename).Worksheets(“Sheet1″).Cells(1, 1)
‘ *** Financial Depth***
Cells(K, 3) = ” Financial Depth”
For g = 1 To 220
If Workbooks(Filename).Worksheets(“Sheet1″).Cells(g, 1) = ” Financial Depth” Then
Cells(K, 4) = Workbooks(Filename).Worksheets(“Sheet1″).Cells(g, 3)
Exit For
End If
Next g
Workbooks(Filename).Saved = True
Workbooks(Filename).Close
Next k
End Sub
This should work for you
Sub Balance()
Dim I As Integer
Dim myfile As String
Dim m as Integer
m = 4
Pathname = “E:\test\”
I = 1
myfile = Dir(Pathname & “*.xls”)
Cells(1, I) = myfile
StartingPoint:
I = I + 1
myfile = Dir
Cells(I, 1) = myfile
If myfile “” Then GoTo StartingPoint
I = I – 1
For K = 1 To I
‘On Error Resume Next
‘ *** workbook name***
Filename = Cells(K, 1)
Workbooks.Open (Pathname & Filename)
‘ *** company name ***
Cells(K, 2) = Workbooks(Filename).Worksheets(“Sheet1″).Cells(1, 1)
‘ *** Financial Depth***
Cells(K, 3) = ” Financial Depth”
For g = 1 To 220
If Workbooks(Filename).Worksheets(“Sheet1″).Cells(g, 1) = ” Financial Depth” Then
Cells(K, m) = Workbooks(Filename).Worksheets(“Sheet1″).Cells(g, 3)
m = m +1
End If
Next g
Can someone please confirm why my macro jumps out of loop. I am not getting why its happening.
My Input looks like this http://i.imgur.com/Y6XRBai.jpg
What I am trying is split the text and write to textfile from column D2 onwards using while loop, First file writes properly but when it starts writing second file either for loop or if condition breaks out and macro comes to line where strDir starts
Sub SplitTextAndSave()
'Macro to split text and write to text file
'Full name of File name will be Single quote + Prefix from B2 + ( + filename from C2 + )'
'Application.DisplayAlerts = False
Dim Val, splitVal As String
Dim reqNumTxt, totLn, reqNum, remChr, i As Integer
Dim wb As Workbook
Dim strFile, fileNm, strDir As String
Set Sheet = Excel.ActiveSheet
' Select where to place the files
Dim obj As Object
Dim path As String
Set obj = CreateObject("Shell.Application").browseforfolder(0, "Please Select Folder where TWS scripts will be created", 0)
On Error GoTo error_trap:
path = obj.self.path & "\"
error_trap:
'this is where it starts again when the loop breaks
strDir = path
filepre = Sheet.Cells(2, 2).Value
reqNum = Sheet.Cells(3, 2).Value
reqNumTxt = 0
Sheet.Cells(2, 4).Activate
Do While ActiveCell.Value <> ""
Set nextcell = ActiveCell.Offset(1, 0)
fileNm = ActiveCell.Offset(0, -1).Value
FileFullNm = strDir & "'" & filepre & "(" & fileNm & ")'"
Open FileFullNm For Output As #1
Val = ActiveCell.Value
totLn = Int(Len(Val) / reqNum)
remChr = Len(Val) Mod reqNum
If Len(Val) <= reqNum Then
Print #1, Val
Close #1
Else
For i = 1 To totLn
'I observed sometimes loop breaks here
splitVal = Left(Right(Val, Len(Val) - reqNumTxt), reqNum)
Print #1, splitVal
reqNumTxt = reqNumTxt + reqNum
Next i
If remChr = 0 Then
Close #1
Else
'most of the time loop break here when writing second file
splitVal = Left(Right(Val, Len(Val) - reqNumTxt), reqNum)
Print #1, splitVal
Close #1
End If
End If
nextcell.Select
Set currentcell = nextcell
'Next
Loop
MsgBox "Done"
'Application.DisplayAlerts = True
End Sub
I added 2 lines to your code and it runs without error. I set splitVal to null and reqNumTxt to zero.
Val = ActiveCell.Value
totLn = Int(Len(Val) / reqNum)
remChr = Len(Val) Mod reqNum
**splitVal = ""**
If Len(Val) <= reqNum Then
Print #1, Val
Close #1
Else
For i = 1 To totLn
'I observed sometimes loop breaks here
splitVal = Left(Right(Val, Len(Val) - reqNumTxt), reqNum)
Print #1, splitVal
reqNumTxt = reqNumTxt + reqNum
Next i
If remChr = 0 Then
Close #1
Else
'most of the time loop break here when writing second file
splitVal = Left(Right(Val, Len(Val) - reqNumTxt), reqNum)
Print #1, splitVal
Close #1
End If
End If
nextcell.Select
Set currentcell = nextcell
**reqNumTxt = 0**
Loop