Extract .xlsx files from folder with OR condition - vba

This code extracts files with names like "M*", and I'd like it to also pull files with names like "X*". Can I simply set an OR condition on the filename parameter? Thanks for your advice!
Worksheets("PMNs").Range("A2:A500").Clear
Application.Calculation = xlManual
Dim Filename, Pathname As String
Dim wb As Workbook
Dim ws As Worksheet
Pathname = ActiveWorkbook.Path & "\"
Filename = Dir(Pathname & "M*.xlsm")
x = 1
Range("A1").Select
Do While Filename <> ""
x = x + 1
' MsgBox (Filename)
Windows("Resource Load Data_fy18.xlsm").Activate 'open data file
Sheets("PMNs").Select
ActiveCell(A & x).Value = Filename 'copy filename to next cell Ax
Filename = Dir()
Loop
Application.Calculation = xlAutomatic
Dim lastrow As Long
lastrow = Cells(Rows.Count, 1).End(xlUp).Row
Range("A2:A" & lastrow).Sort key1:=Range("A2:A" & lastrow), _
order1:=xlAscending, Header:=xlNo
End Sub

Slightly change the way you open the files:
Dim Filename as String, Pathname As String
Dim wb As Workbook
Dim ws As Worksheet
Pathname = ActiveWorkbook.Path & "\"
x = 1
Range("A1").Select
Dim StrFile As String
StrFile = Dir(Pathname)
Do While Len(StrFile) > 0
If (Left(StrFile, 1) = "M" Or Left(StrFile, 1) = "X") and right(StrFile,4) = "xlsm" Then
Debug.print(StrFile) ' prints the file name and extension
' Do stuff here!
End If
Filename = Dir
Loop

Related

Output in a different workbook

I've created a tool and the below macro copies all .csv files into a excel sheet. I want the data to be copied to the "Consol.xlsx" file that I created. The current code copies the data in the tool not the "Consol.xlsx" file. I am unable to update the code so that the data gets copied correctly.
Below is my code:
Sub Button_click2()
Call AddNew
Call ImportCSVsWithReference
End Sub
Sub AddNew()
Application.DisplayAlerts = False
Dim thisWb As Workbook
Set thisWb = ActiveWorkbook
Workbooks.Add
ActiveWorkbook.SaveAs Filename:=thisWb.path & "\Consol.xlsx"
Application.DisplayAlerts = True
End Sub
Sub ImportCSV()
Dim strSourcePath As String
Dim strDestPath As String
Dim strFile As String
Dim strData As String
Dim x As Variant
Dim Cnt As Long
Dim r As Long
Dim c As Long
Application.ScreenUpdating = False
'Change the path to the source folder accordingly
strSourcePath = Application.ActiveWorkbook.path
If Right(strSourcePath, 1) <> "\" Then strSourcePath = strSourcePath & "\"
'Change the path to the destination folder accordingly
strDestPath = Application.ActiveWorkbook.path
If Right(strDestPath, 1) <> "\" Then strDestPath = strDestPath & "\"
strFile = Dir(strSourcePath & "*.csv")
Do While Len(strFile) > 0
Cnt = Cnt + 1
r = Cells(Rows.count, "A").End(xlUp).Row + 1
Open strSourcePath & strFile For Input As #1
Do Until EOF(1)
Line Input #1, strData
x = Split(strData, ",")
For c = 0 To UBound(x)
Cells(r, c + 1).Value = Trim(x(c))
Next c
r = r + 1
Loop
Close #1
Name strSourcePath & strFile As strDestPath & strFile
strFile = Dir
Loop
Application.ScreenUpdating = True
If Cnt = 0 Then _
MsgBox "No CSV files were found...", vbExclamation
End Sub
Well it looks like you've got both of the pieces there. Your first subroutine saves a blank workbook called consol.xlsx.
Then, your second subroutine loops through the directory, opens each csv file, and copes it to some unspecified range.
What I would insert before your loop is:
Set wbkConsol = Workbooks.Open(thisWorkbook.path & "\Consol.xlsx")
Then, during your loop over the CSV files:
strFile = Dir(strSourcePath & "*.csv")
Do While Len(strFile) > 0
Cnt = Cnt + 1
r = Cells(Rows.count, "A").End(xlUp).Row + 1
Open strSourcePath & strFile For Input As #1
Do Until EOF(1)
Line Input #1, strData
' Set wshAdd = wbkConsol.Worksheets.Add() ' New ws in wbk
' wshAdd.Name = left(strFile, 31) ' First 31-chars of filename.
x = Split(strData, ",")
For c = 0 To UBound(x)
wshAdd.Cells(r, c + 1).Value = Trim(x(c))
Next c
r = r + 1
Loop
Close #1
Name strSourcePath & strFile As strDestPath & strFile
strFile = Dir()
Loop
As an added note: you could pass your workbook from your first sub to the second sub, by reference. That way, you won't have to open it up again. This would be by combining the button click into just a single command.
Sub1()
wbkConsol = workbooks.Add
Call sub2(wbkConsol)
End sub

copying data from a folder of workbooks into a single worksheet iteration through loop in VBA

I am trying to copy data from a couple of workbooks present in a folder into a single workbook. I am looping through the folder to fetch the data from the various workbooks but I need to paste the data spanning from A5:D5 in loop.
i.e A5:D5 in the destination sheet is one workbook's data in the folder, I need the other set of data to be copied into A6:D6 and so on for the number of workbooks in the folder. Please help me loop through this.
Private Sub CommandButton1_Click()
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Path = "D:\Macro_Demo\estimation_sheets\"
Filename = Dir(Path & "*.xls")
Set target = Workbooks.Open("D:\Macro_Demo\Metrics_Macro_dest")
'--------------------------------------------
'OPEN EXCEL FILES
Do While Len(Filename) > 0 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(Path & Filename)
target.Sheets("Metrics_Data").Range("A5").Value = wbk.Sheets("summary").Range("I5").Value
target.Sheets("Metrics_Data").Range("B5").Value = wbk.Sheets("summary").Range("I6").Value + wbk.Sheets("summary").Range("I7")
target.Sheets("Metrics_Data").Range("C5").Value = wbk.Sheets("summary").Range("I8").Value
target.Sheets("Metrics_Data").Range("D5").Value = wbk.Sheets("summary").Range("I9").Value
MsgBox Filename & " has opened"
wbk.Close True
Filename = Dir
Loop
MsgBox "Task complete!"
End Sub
Try this:
Private Sub CommandButton1_Click()
Dim wbk As Workbook, target As Workbook, excelFile As String, path As String, rw As Integer
path = "D:\Macro_Demo\estimation_sheets\"
excelFile = Dir(path & "*.xls")
rw = 5
Set target = Workbooks.Open("D:\Macro_Demo\Metrics_Macro_dest")
Do While excelFile <> ""
Set wbk = Workbooks.Open(path & excelFile)
With target.Sheets("Metrics_Data")
.Range("A" & rw) = wbk.Sheets("summary").Range("I5")
.Range("B" & rw) = wbk.Sheets("summary").Range("I6") + wbk.Sheets("summary").Range("I7")
.Range("C" & rw) = wbk.Sheets("summary").Range("I8")
.Range("D" & rw) = wbk.Sheets("summary").Range("I9")
End With
wbk.Close True
rw = rw + 1
excelFile = Dir
Loop
MsgBox "Task complete!"
End Sub
You need to find the next available row on your destination sheet, store that in a variable, and write the data relative to that cell. Like this
Private Sub CommandButton1_Click()
Dim shSource As Worksheet, shDest As Worksheet
Dim sFile As String
Dim rNextRow As Range
Const sPATH As String = "D:\Macro_Demo\estimation_sheets\"
'Open the destination workbook
Set shDest = Workbooks.Open("D:\Macro_Demo\Metrics_Macro_dest.xls").Worksheets("Metrics_Data")
sFile = Dir(sPATH & "*.xls")
Do While Len(sFile) > 0
Set shSource = Workbooks.Open(sPATH & sFile).Worksheets("summary")
'start at row 1000 and go up until you find something
'then go down one row
Set rNextRow = shDest.Cells(1000, 1).End(xlUp).Offset(1, 0)
'Write the values relative to rNextRow
With rNextRow
.Value = shSource.Range("I5").Value
.Offset(0, 1).Value = shSource.Range("I6").Value
.Offset(0, 2).Value = shSource.Range("I8").Value
.Offset(0, 3).Value = shSource.Range("I9").Value
End With
'Close the source
shSource.Parent.Close False
sFile = Dir
Loop
MsgBox "Done"
End Sub

VBA Get File Name From Path and Store it to a Cell [duplicate]

This question already has answers here:
How do you get just the filename rather than the entire file path of an open file?
(6 answers)
Closed 8 years ago.
I'm working on some code that I would like to find the path of a selected file, extract the file name, and then write the file name to a cell on the sheet. Here's what I have so far:
Private Sub CommandButton3_Click()
Sheets("Raw Data").Unprotect
Application.DisplayAlerts = False
Sheets("Raw Data").Delete
Sheets.Add After:=Worksheets(1)
Worksheets(2).Name = "Raw Data"
Application.DisplayAlerts = True
Dim basebook As Workbook
Dim mybook As Workbook
Dim sourceRange As Range
Dim destrange As Range
Dim SourceRcount As Long
Dim n As Long
Dim MyPath As String
Dim SaveDriveDir As String
Dim FName As Variant
SaveDriveDir = CurDir
MyPath = "H:"
ChDrive MyPath
ChDir MyPath
FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xls), *.xls", MultiSelect:=True)
If IsArray(FName) Then
Application.ScreenUpdating = False
Set basebook = ThisWorkbook
For n = LBound(FName) To UBound(FName)
Set mybook = Workbooks.Open(FName(n))
Set sourceRange = mybook.Worksheets(1).Cells
SourceRcount = sourceRange.Rows.Count
Set destrange = basebook.Sheets("Raw Data").Cells
sourceRange.Copy destrange
mybook.Close True
Next
End If
ChDrive SaveDriveDir
ChDir SaveDriveDir
Application.ScreenUpdating = True
Sheets("Main").Select
Cells(5, 4).Value = FName
Sheets("CS-CRM Raw Data").Select
ActiveSheet.Cells(1, 1).Select
Sheets("Raw Data").Protect
End Sub
So far the code will get the path from this line:
FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xls), *.xls", MultiSelect:=True)
And it will write it to a cell with these lines:
Sheets("Main").Select
Cells(5, 4).Value = FName
However, every time I try to get it to just get the file name it doesn't work. I'll either get an error message or it will just post the entire path again. Does anyone know the best way to do this?
Here is a way to parse the result of GetOpenFileName() into three parts:
path
filename
file extension
..
Sub qwerty()
Dim f As String, Path As String, _
FileName As String, FileType As String
f = Application.GetOpenFilename()
ary = Split(f, "\")
bry = Split(ary(UBound(ary)), ".")
ary(UBound(ary)) = ""
Path = Join(ary, "\")
FileName = bry(0)
FileType = bry(1)
Range("A1") = Path
Range("A2") = FileName
Range("A3") = FileType
End Sub
For example:
You should also bear in mind that they could select more than 1 file;
Sub getfilenames()
FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xls), *.xls", _
MultiSelect:=True)
i = 1
For n = LBound(FName) To UBound(FName)
FnameInLoop = Right(FName(n), Len(FName(n)) - InStrRev(FName(n), _
Application.PathSeparator, , 1))
Cells(i, 4).Value = FnameInLoop
i = i + 1
Next n
End Sub

VB script to work for loading objects from local directory with specified names on Range B

I wanted to write a code for macro, that will load files from my local directory into excel sheet of Column say ("C"), the names on files should match names on Column ("B"). If any of the files doesn't find for the names given in column B it should skip that row of loading files and continues to next column. I'am difficulty in writing as I am new to VB. I tried somehow but, my script working to load files from directory and loading names. Please help!! thank you all,
Code:
Sub Insert_OLE_Object()
Dim mainWorkBook As Workbook
Set mainWorkBook = ActiveWorkbook
Set ActiveSheet = example1
Folderpath = "C:\Documents and Settings\my\Desktop\folder1"
Set fso = CreateObject("Scripting.FileSystemObject")
NoOfFiles = fso.GetFolder(Folderpath).Files.Count
Set listfiles = fso.GetFolder(Folderpath).Files
For Each fls In listfiles
Counter = Counter + 1
Range("B" & Counter).Value = fls.Name
strCompFilePath = Folderpath & "\" & Trim(fls.Name)
If strCompFilePath <> "" Then
Worksheets("Example1").OLEObjects.Add(Filename:=strCompFilePath, Link:=False, DisplayAsIcon:=True, IconIndex:=1, IconLabel:=strCompFilePath, Left:=20, Top:=40, Width:=150, Height:=10).Select
Sheets("example1").Activate
Sheets("example1").Range("C" & ((Counter - 1) * 3) + 1).Select
End If
Next
End Sub
Try this code:
Sub Insert_OLE_Object()
Dim ws As Worksheet
Dim rng As Range, c As Range
Dim strCompFilePath As String, Folderpath As String, fullpath As String
Dim obj As Object
Application.ScreenUpdating = False
'change to suit
Set ws = ThisWorkbook.Worksheets("Example1")
'change B1:B5 to suit
Set rng = ws.Range("B1:B5")
Folderpath = "C:\Documents and Settings\my\Desktop\folder1"
For Each c In rng
strCompFilePath = Dir(Folderpath & "\" & Trim(c.Value) & ".*")
'if file with this name found, embed it
If strCompFilePath <> "" Then
fullpath = Folderpath & "\" & strCompFilePath
Set obj = ws.OLEObjects.Add(Filename:=fullpath, Link:=False, _
DisplayAsIcon:=True, IconIndex:=1, _
IconLabel:=fullpath)
With obj
.Left = c.Offset(, 1).Left
.Top = c.Offset(, 1).Top
.Width = c.Offset(, 1).ColumnWidth
.Height = c.Offset(, 1).RowHeight
End With
End If
Next
Application.ScreenUpdating = True
End Sub

Xls to CSV macro Conversion format for numbers

I have a macro 'macro1' that convert all *.xls files within a folder to *.csv. After converting them, I merge rows using the command prompt. The I convert the merged file into an xls using macro2. Everything is working fine but when a value is something like 123456789123456 the resulting csv value is something like 1234E+11. How to keep the number format between converted files?
here are my macros
macro1
Option Explicit
Sub ConvertToCSV()
Dim i As Long
Dim NumFiles As Long
Dim FileName As String
Dim FileNames() As String
FileName = Dir(ThisWorkbook.Path & "/*.xls")
NumFiles = 1
ReDim Preserve FileNames(1 To NumFiles)
FileNames(NumFiles) = FileName
Do While FileName <> ""
FileName = Dir()
If FileName <> "" Then
NumFiles = NumFiles + 1
ReDim Preserve FileNames(1 To NumFiles)
FileNames(NumFiles) = FileName
End If
Loop
Application.DisplayAlerts = False
For i = 1 To UBound(FileNames)
If FileNames(i) <> ThisWorkbook.Name Then
Workbooks.Open FileName:=ThisWorkbook.Path & "\" & FileNames(i)
ActiveWorkbook.SaveAs _
FileName:=Left(FileNames(i), Len(FileNames(i)) - 4) & ".csv", _
FileFormat:=xlCSV
ActiveWorkbook.Close
End If
Next i
Application.DisplayAlerts = True
End Sub
and the macro2
Sub FromCSVToXLS()
Dim myWB As Workbook, WB As Workbook
Dim L As Long, x As Long, i As Long
Dim v As Variant
Dim myPath
Dim myFile
Set myWB = ThisWorkbook
Application.ScreenUpdating = False
Sheets(1).Cells.ClearContents
myPath = "C:\Folder1\Folder2\" '<<< change path
myFile = "myFile.csv" '<<< change file name
Set WB = Workbooks.Open(myPath & myFile)
ActiveSheet.UsedRange.Copy myWB.Sheets(1).Range("A1")
ActiveWorkbook.Close False
L = myWB.Sheets(1).UsedRange.Rows.Count
For i = 1 To L
v = Split(Cells(i, 1), ",")
For x = 0 To UBound(v)
Cells(i, x + 1) = v(x)
Next x
Next i
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:= "D:\data folder\1.xls"
Application.DisplayAlerts = True
myWB.Save
Application.ScreenUpdating = True
End Sub
PS: the command prompt is not altering the number format. VERIFIED!
Thank you
SOLVED!!
I did this:
Open the merged file
select the concerned column
right clic on the column
and I changed the format of all column's cells.