I'm trying to merge multiple Excel workbooks into a single sheet.
I found code to choose the folder and merge all the Excel files in the folder into current active workbook.
The target workbook consists of two sheets which is PID and Services.
Option Explicit
Public strPath As String
Public Type SELECTINFO
hOwner As Long
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type
Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Declare Function SHBrowseForFolder Lib "shell32.dll" Alias "SHBrowseForFolderA" (lpBrowseInfo As SELECTINFO) As Long
Function SelectFolder(Optional Msg) As String
Dim sInfo As SELECTINFO
Dim path As String
Dim r As Long, x As Long, pos As Integer
sInfo.pidlRoot = 0&
If IsMissing(Msg) Then
sInfo.lpszTitle = "Select your folder."
Else
sInfo.lpszTitle = Msg
End If
sInfo.ulFlags = &H1
x = SHBrowseForFolder(sInfo)
path = Space$(512)
r = SHGetPathFromIDList(ByVal x, ByVal path)
If r Then
pos = InStr(path, Chr$(0))
SelectFolder = Left(path, pos - 1)
Else
SelectFolder = ""
End If
End Function
' "Merging Part"
Sub MergeExcels()
Dim path As String, ThisWB As String, lngFilecounter As Long
Dim wbDest As Workbook, shtDest As Worksheet, ws As Worksheet
Dim Filename As String, Wkb As Workbook
Dim CopyRng As Range, Dest As Range
Dim RowofCopySheet As Integer
RowofCopySheet = 1
ThisWB = ActiveWorkbook.Name
path = SelectFolder("Select a folder containing Excel files you want to merge")
Application.EnableEvents = False
Application.ScreenUpdating = False
Set shtDest = ActiveWorkbook.Sheets(1)
Filename = Dir(path & "\*.xls", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = vbNullString
If Not Filename = ThisWB Then
Set Wkb = Workbooks.Open(Filename:=path & "\" & Filename)
Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(ActiveSheet.UsedRange.Rows.Count, ActiveSheet.UsedRange.Columns.Count))
Set Dest = shtDest.Range("A" & shtDest.UsedRange.SpecialCells(xlCellTypeLastCell).Row + 1)
CopyRng.Copy Dest
Wkb.Close False
End If
Filename = Dir()
Loop
Range("A1").Select
Application.EnableEvents = True
Application.ScreenUpdating = True
MsgBox "Files Merged!"
End Sub
I need to copy Sheet1 (PID) and Sheet2 (Services). The code merges sheet1 (PID) only.
I tried to tweak the code.
Set shtDest = ActiveWorkbook.Sheets(1)
Filename = Dir(path & "\*.xls", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = vbNullString
If Not Filename = ThisWB Then
Set Wkb = Workbooks.Open(Filename:=path & "\" & Filename)
Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(ActiveSheet.UsedRange.Rows.Count, ActiveSheet.UsedRange.Columns.Count))
Set Dest = shtDest.Range("A" & shtDest.UsedRange.SpecialCells(xlCellTypeLastCell).Row + 1)
CopyRng.Copy Dest
Wkb.Close False
End If
I tried to change
ActiveWorkbook.Sheets(1) to ActiveWorkbook.Sheets(2) and
Set CopyRng = Wkb.Sheets(1) to Set CopyRng = Wkb.Sheets(2).
after tweaking and testing the code, i managed to find the way. The solution is just add "Wkb.Sheets(2).Activate" and the change Set CopyRng = Wkb.Sheets(1) to Set CopyRng = Wkb.Sheets(2) to merge the second sheet. Below are the sample code.
Set shtDest = ActiveWorkbook.Sheets(1)
Filename = Dir(path & "\*.xls", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = vbNullString
If Not Filename = ThisWB Then
Set Wkb = Workbooks.Open(Filename:=path & "\" & Filename)
Wkb.Sheets(2).Activate
Set CopyRng = Wkb.Sheets(2).Range(Cells(RowofCopySheet, 1), Cells(ActiveSheet.UsedRange.Rows.Count, ActiveSheet.UsedRange.Columns.Count))
Set Dest = shtDest.Range("A" & shtDest.UsedRange.SpecialCells(xlCellTypeLastCell).Row)
CopyRng.Copy Dest
Wkb.Close False
End If
Related
When trying to copy range("A2:H2") + End(xlDown) from multiple files into master Workbook
Run time error '424' Object Required
Sub Create()
Dim folderPath As String
Dim fileName As String
Dim erow As Long
Dim wbMaster As Workbook, wbTemp As Workbook
Dim wsMaster As Worksheet, wsTemp As Worksheet
folderPath= "\\Groups\DAILY RECON\October 2021"
Set wbMaster = ActiveWorkbook
Set wsMaster = wbMaster.Sheets("NY")
if Right(folderPath, 1)<> "\" Then folderPath = folderPath & "\"
fileName = Dir(folderPath & "*.xlsm")
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
Do While fileName<>""
if fileName <> "master.xlsm" Then
Set wbTemp = Workbooks.Open(folderPath & fileName, ReadOnly= True)
Set wsTemp = wbTemp.Sheets("NY")
With wsMaster
erow = .Range("A" & .Rows.Count).End(xlUp).Row
ws.Temp.Range("A2:H2").Select ' ----> **Error**
Range(ActiveCell,ActiveCell.End(xlDown)).Select
Selection.Copy
.Range("A" & erow).Offset(1,0).PasteSpecial xlPasteValues
End With
wbTemp.Close False
Set wsTemp = Nothing
Set wbTemp = Nothing
End If
fileName = Dir
Loop
MsgBox "Finished"
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub
Copy Range From Multiple Files
Option Explicit
Sub Create()
Dim wbMaster As Workbook, wbTemp As Workbook
Dim wsMaster As Worksheet, wsTemp As Worksheet
Dim mrg As Range, trg As Range
Dim mrrg As Range
Dim meRow As Long
Dim mFileName As String, tFileName As String
Dim tFolderPath As String
Dim rCount As Long
Dim cCount As Long
tFolderPath = "\\Groups\DAILY RECON\October 2021"
Set wbMaster = ActiveWorkbook ' ThisWorkbook ' workbook containing this code
Set wsMaster = wbMaster.Sheets("NY")
With wsMaster
meRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1
cCount = wsMaster.Columns("A:H").Columns.Count
Set mrrg = .Range("A" & meRow).Resize(, cCount)
End With
mFileName = wbMaster.Name
If Right(tFolderPath, 1) <> "\" Then tFolderPath = tFolderPath & "\"
tFileName = Dir(tFolderPath & "*.xlsm")
Application.ScreenUpdating = False
Do While tFileName <> ""
If StrComp(tFileName, mFileName, vbTextCompare) <> 0 Then
Set wbTemp = Workbooks.Open(tFolderPath & tFileName, ReadOnly:=True)
On Error Resume Next ' check if exists
Set wsTemp = wbTemp.Sheets("NY")
On Error GoTo 0
If Not wsTemp Is Nothing Then ' it exists
With wsTemp.Range("A1").CurrentRegion.Columns("A:H")
Set trg = .Resize(.Rows.Count - 1).Offset(1)
End With
rCount = trg.Rows.Count
Set mrg = mrrg.Resize(rCount)
mrg.Value = trg.Value
Set mrrg = mrrg.Offset(rCount)
Set wsTemp = Nothing
End If
wbTemp.Close SaveChanges:=False
End If
tFileName = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Finished"
End Sub
So I came around the net to find answers for this but found none, what I want my code to do is open a worksheet from a folder get the photo from that worksheet and finally paste to a comment inside a cell in my current workbook. here's my code
Dim folder As String
Private Sub Workbook_Open()
folder = ThisWorkbook.path
End Sub
Sub populatePDA()
'Application.ScreenUpdating = False
Dim wb As Workbook
Dim ws As Variant
Dim path As String
Dim fileName As String
Dim p As Picture
Dim img As Variant
Dim cb As Comment
Set ws = ThisWorkbook.Sheets("PDA")
path = folder & "\PDA\"
fileCount = 0
fileName = Dir(path & "*.xlsm")
Do While fileName <> ""
Set wb = Workbooks.Open(path & fileName) 'Open Workbook
ws.Range("A3:F3").Insert (xlShiftDown)
ws.Range("A3") = wb.Sheets(1).Range("B16").Value 'Item Name
ws.Range("B3") = wb.Sheets(1).Range("B17").Value 'S/N
ws.Range("C3") = wb.Sheets(1).Range("G7").Value 'Description
ws.Range("D3") = wb.Sheets(1).Range("H12").Value 'Calibration
ws.Range("E3") = wb.Sheets(1).Range("H13").Value 'Expiration
For Each p In wb.Sheets(1).Pictures
p.CopyPicture
Set img = ws.Paste
Set cb = ws.Range("F3").AddComment
cb.Text Text:=""
cb.Shape.Fill.UserPicture (img)
Next p
wb.Close
fileName = Dir
Loop
'Application.ScreenUpdating = True
End Sub
You do not say anything and I finished something...
I modified a little your code making it to add a new insertion in the working sheet, for a new open file, and process them as (I understood) you need. Please, test the next code:
Sub populatePDA()
Dim fileName As String, path As String
Dim ws As Worksheet, wb As Workbook, p As Shape, fileCount As Long
Dim cb As Comment, i As Long, arrCol As Variant, k As Long
arrCol = Split("A,B,C,D,E", ",")
Set ws = ThisWorkbook.Sheets("PDA")
path = ThisWorkbook.path & "\PDA\"
fileCount = 0
fileName = Dir(path & "*.xlsm")
k = 2
Application.ScreenUpdating = False
Do While fileName <> ""
Set wb = Workbooks.Open(path & fileName) 'Open Workbook
k = k + 1
ws.Range("A" & k & ":E" & k).Insert (xlShiftDown)
ws.Range("A" & k) = wb.Sheets(1).Range("B16").Value 'Item Name
ws.Range("B" & k) = wb.Sheets(1).Range("B17").Value 'S/N
ws.Range("C" & k) = wb.Sheets(1).Range("G7").Value 'Description
ws.Range("D" & k) = wb.Sheets(1).Range("H12").Value 'Calibration
ws.Range("E" & k) = wb.Sheets(1).Range("H13").Value 'Expiration
i = 2
For Each p In wb.Sheets(1).Shapes
If p.Type = msoPicture Then
i = i + 1
ws.Activate
If Not ws.Range(arrCol(i - 3) & k).Comment Is Nothing Then _
ws.Range(arrCol(i - 3) & k).Comment.Delete
Set cb = ws.Range(arrCol(i - 3) & k).AddComment
cb.text text:=""
With cb.Shape
.width = p.width: .height = p.height
End With
cb.Shape.Fill.UserPicture (SelImPathCh(p, wb))
End If
Next p
ws.Activate
wb.Close False
fileName = Dir
Loop
ws.UsedRange.EntireColumn.AutoFit
Application.ScreenUpdating = False
End Sub
The function able to make the picture insertion is the next (it is called by the main above code):
Private Function SelImPathCh(img As Shape, Optional wb As Workbook) As String
Dim ch As ChartObject, sh As Worksheet, sFile As String
If Not wb Is Nothing Then Set sh = wb.Sheets(1)
sFile = ThisWorkbook.path & "\Pict1.jpg"
Set ch = sh.ChartObjects.Add(left:=1, _
top:=1, width:=img.width, _
height:=img.height)
If Not wb Is Nothing Then wb.Activate: sh.Activate
img.Copy: ch.Activate: ActiveChart.Paste
ch.Chart.Export sFile
ch.Delete
SelImPathCh = sFile
End Function
The wb variable is Optional only for my testing need. I used a sheet of the existing working workbook and I skipped it when called the function...
UserPicture works with file path. Try below method, it should work.
Set cb = Worksheets(2).Range("F3").AddComment
cb.Text Text:=""
cb.Shape.Fill.UserPicture ("FILE_PATH")
And if you want to copy picture from worksheet only, then you can export the pictures in tmp folder using the following code and then give the same path in UserPicture.
Sub SaveImages()
Dim shpName As Variant
Dim shp As Shape
Dim ppt As Object, ps As Variant, slide As Variant
Set ppt = CreateObject("PowerPoint.application")
Set ps = ppt.presentations.Add
Set slide = ps.slides.Add(1, 1)
For Each shp In ActiveSheet.Shapes
shpName = "D:\\tmp.jpg"
shp.Copy
With slide
.Shapes.Paste
.Shapes(.Shapes.Count).Export shpName, 2
.Shapes(.Shapes.Count).Delete
End With
Next shp
With ps
.Saved = True
.Close
End With
ppt.Quit
Set ppt = Nothing
End Sub
Scenario: I have tons of Invoices received in my e-mail and saving them in a folder("C:\Users\Vbattul2\Desktop\Invoices\") and manually opening them one by one copying the needed data and pasting them to my excel tracker. Note that all the invoices have the same formats.
Opportunity to Automate: Automate the process of copy and paste of needed data from pdf and paste it to excel dummy worksheet(data delimited with colon & blank) and paste cell references in Excel invoice tracker.
Design: I will need to copy the pdf and paste it to a dummy worksheet then paste it to my excel invoice tracker.
I tried running this code from a thread posted 3 years ago:
VBA Copying data from pdf
I couldn't seem to understand this line, so it is returning me an
error: 1004 Method 'Range' of object'_Global failed
Line Error: For Each fName In Range("path")
I also tried replacing the ("path") to my folder path where I save all the invoices but it doesn't work.
Sub StartAdobe1()
Dim fName As Variant
Dim wbTransfer As Excel.Workbook
Dim wsNew As Excel.Worksheet
Dim dOpenCol As Double
Dim oPDFApp As AcroApp
Dim oAVDoc As AcroAVDoc
Dim oPDDoc As AcroPDDoc
'Define your spreadsheet
Set wbTransfer = Workbooks("transfer.xlsm")
Set wsNew = wbTransfer.Sheets("new")
'Find first open column
dOpenCol = wsNew.Cells(1, Columns.Count).End(xlToLeft).Column + 1
'Instantiate Acrobat Objects
Set oPDFApp = CreateObject("AcroExch.App")
Set oAVDoc = CreateObject("AcroExch.AVDoc")
Set oPDDoc = CreateObject("AcroExch.PDDoc")
For Each fName In Range("path")
'Open the PDF file. The AcroAVDoc.Open function returns a true/false
'to tell you if it worked
If oAVDoc.Open(fName.Text, "") = True Then
Set oPDDoc = oAVDoc.GetPDDoc
Else
Debug.Assert False
End If
'Copy all using Acrobat menu
oPDFApp.MenuItemExecute ("SelectAll")
oPDFApp.MenuItemExecute ("Copy")
'Paste into open column
wbTransfer.Activate
wsNew.Cells(1, dOpenCol).Select
ActiveSheet.Paste
'Select next open column
dOpenCol = dOpenCol + 1
oAVDoc.Close (1) '(1)=Do not save changes
oPDDoc.Close
Next
'Clean up
Set wbTransfer = Nothing
Set wsNew = Nothing
Set oPDFApp = Nothing
Set oAVDoc = Nothing
Set oPDDoc = Nothing
End Sub
i have uploaded an attachment where the actual result in dummy worksheet(paste as delimited values - colon & blank) should look like and the excel invoice tracker.
here are the links.
https://www.dropbox.com/preview/Marketing/desired%20output%20from%20pdf%20to%20excel.xlsm?role=work
https://www.dropbox.com/preview/Marketing/MRC%201380%20INVENTORY%202019.xlsb?role=work
So , what do you have now, all Excel files or all text files?
If all Excel files, try this.
Note: Copy all code below in a normal module of your workbook
#If VBA7 Then
Declare PtrSafe Function SetCurrentDirectoryA Lib _
"kernel32" (ByVal lpPathName As String) As Long
#Else
Declare Function SetCurrentDirectoryA Lib _
"kernel32" (ByVal lpPathName As String) As Long
#End If
Sub ChDirNet(szPath As String)
SetCurrentDirectoryA szPath
End Sub
Sub Basic_Example_2()
Dim MyPath As String
Dim SourceRcount As Long, Fnum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
Dim SaveDriveDir As String
Dim FName As Variant
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
SaveDriveDir = CurDir
ChDirNet "C:\Users\Ron\test"
FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
MultiSelect:=True)
If IsArray(FName) Then
'Add a new workbook with one sheet
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1
'Loop through all files in the array(myFiles)
For Fnum = LBound(FName) To UBound(FName)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(FName(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
With mybook.Worksheets(1)
Set sourceRange = .Range("A1:C1")
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
'if SourceRange use all columns then skip this file
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceRcount = sourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "Sorry there are not enough rows in the sheet"
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
'Copy the file name in column A
With sourceRange
BaseWks.Cells(rnum, "A"). _
Resize(.Rows.Count).Value = FName(Fnum)
End With
'Set the destrange
Set destrange = BaseWks.Range("B" & rnum)
'we copy the values from the sourceRange to the destrange
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If
Next Fnum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
ChDirNet SaveDriveDir
End Sub
If all text files, try this.
Option Explicit
#If VBA7 Then
Private Declare PtrSafe Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, _
ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long
Private Declare PtrSafe Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, _
lpExitCode As Long) As Long
#Else
Private Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, _
ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, _
lpExitCode As Long) As Long
#End If
Public Const PROCESS_QUERY_INFORMATION = &H400
Public Const STILL_ACTIVE = &H103
Public Sub ShellAndWait(ByVal PathName As String, Optional WindowState)
Dim hProg As Long
Dim hProcess As Long, ExitCode As Long
'fill in the missing parameter and execute the program
If IsMissing(WindowState) Then WindowState = 1
hProg = Shell(PathName, WindowState)
'hProg is a "process ID under Win32. To get the process handle:
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, False, hProg)
Do
'populate Exitcode variable
GetExitCodeProcess hProcess, ExitCode
DoEvents
Loop While ExitCode = STILL_ACTIVE
End Sub
Sub Merge_CSV_Files()
Dim BatFileName As String
Dim TXTFileName As String
Dim XLSFileName As String
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim DefPath As String
Dim Wb As Workbook
Dim oApp As Object
Dim oFolder
Dim foldername
'Create two temporary file names
BatFileName = Environ("Temp") & _
"\CollectCSVData" & Format(Now, "dd-mm-yy-h-mm-ss") & ".bat"
TXTFileName = Environ("Temp") & _
"\AllCSV" & Format(Now, "dd-mm-yy-h-mm-ss") & ".txt"
'Folder where you want to save the Excel file
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
'Set the extension and file format
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007 or higher
FileExtStr = ".xlsx": FileFormatNum = 51
'If you want to save as xls(97-2003 format) in 2007 use
'FileExtStr = ".xls": FileFormatNum = 56
End If
'Name of the Excel file with a date/time stamp
XLSFileName = DefPath & "MasterCSV " & _
Format(Now, "dd-mmm-yyyy h-mm-ss") & FileExtStr
'Browse to the folder with CSV files
Set oApp = CreateObject("Shell.Application")
Set oFolder = oApp.BrowseForFolder(0, "Select folder with CSV files", 512)
If Not oFolder Is Nothing Then
foldername = oFolder.Self.Path
If Right(foldername, 1) <> "\" Then
foldername = foldername & "\"
End If
'Create the bat file
Open BatFileName For Output As #1
Print #1, "Copy " & Chr(34) & foldername & "*.csv" _
& Chr(34) & " " & TXTFileName
Close #1
'Run the Bat file to collect all data from the CSV files into a TXT file
ShellAndWait BatFileName, 0
If Dir(TXTFileName) = "" Then
MsgBox "There are no csv files in this folder"
Kill BatFileName
Exit Sub
End If
'Open the TXT file in Excel
Application.ScreenUpdating = False
Workbooks.OpenText Filename:=TXTFileName, Origin:=xlWindows, StartRow _
:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, Comma:=True, _
Space:=False, Other:=False
'Save text file as a Excel file
Set Wb = ActiveWorkbook
Application.DisplayAlerts = False
Wb.SaveAs Filename:=XLSFileName, FileFormat:=FileFormatNum
Application.DisplayAlerts = True
Wb.Close savechanges:=False
MsgBox "You find the Excel file here: " & vbNewLine & XLSFileName
'Delete the bat and text file you temporary used
Kill BatFileName
Kill TXTFileName
Application.ScreenUpdating = True
End If
End Sub
See the link below for all details.
https://www.rondebruin.nl/win/section3.htm
Also, consider using this very useful Excel AddIn.
https://www.rondebruin.nl/win/addins/rdbmerge.htm
You would probably well served if you first convert all PDF files into text files, and import all data from all text files into Multiple sheets in Excel.
Sub convertpdf2()
Dim AcroXApp As Acrobat.AcroApp
Dim AcroXAVDoc As Acrobat.AcroAVDoc
Dim AcroXPDDoc As Acrobat.AcroPDDoc
Dim Filename As String
Dim jsObj As Object
Dim NewFileName As String
Filename = "C:\your_path_here\test.pdf"
NewFileName = "C:\your_path_here\Desktop\test.txt"
Set AcroXApp = CreateObject("AcroExch.App")
'AcroXApp.Show
Set AcroXAVDoc = CreateObject("AcroExch.AVDoc")
AcroXAVDoc.Open Filename, "Acrobat"
Set AcroXPDDoc = AcroXAVDoc.GetPDDoc
Set jsObj = AcroXPDDoc.GetJSObject
jsObj.SaveAs NewFileName, "com.adobe.acrobat.plain-text"
AcroXAVDoc.Close False
AcroXApp.Hide
AcroXApp.Exit
End Sub
Or, put everything in all the text files into one single sheet in Excel, assuming all files have the same schema, of course.
Import several test files into separate sheets in Excel.
Sub CombineTextFiles()
'updateby Extendoffice 20151015
Dim xFilesToOpen As Variant
Dim I As Integer
Dim xWb As Workbook
Dim xTempWb As Workbook
Dim xDelimiter As String
Dim xScreen As Boolean
On Error GoTo ErrHandler
xScreen = Application.ScreenUpdating
Application.ScreenUpdating = False
xDelimiter = "|"
xFilesToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Kutools for Excel", , True)
If TypeName(xFilesToOpen) = "Boolean" Then
MsgBox "No files were selected", , "Kutools for Excel"
GoTo ExitHandler
End If
I = 1
Set xTempWb = Workbooks.Open(xFilesToOpen(I))
xTempWb.Sheets(1).Copy
Set xWb = Application.ActiveWorkbook
xTempWb.Close False
xWb.Worksheets(I).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
Do While I < UBound(xFilesToOpen)
I = I + 1
Set xTempWb = Workbooks.Open(xFilesToOpen(I))
With xWb
xTempWb.Sheets(1).Move after:=.Sheets(.Sheets.Count)
.Worksheets(I).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=xDelimiter
End With
Loop
ExitHandler:
Application.ScreenUpdating = xScreen
Set xWb = Nothing
Set xTempWb = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description, , "Kutools for Excel"
Resume ExitHandler
End Sub
If you have Acrobat installed, you can try the script below.
Sub Convert_to_TXT()
Dim AcroXApp As Acrobat.AcroApp
Dim AcroXAVDoc As Acrobat.AcroAVDoc
Dim AcroXPDDoc As Acrobat.AcroPDDoc
Dim Filename As String
Dim jsObj As Object
Dim NewFileName As String
Const sPath = "C:\Users\Excel\Desktop\test\"
Const sExt = ".pdf"
Const dPath = "C:\Users\Excel\Desktop\test\"
Const dExt = ".txt"
Dim sName As String, dName As String, fCount As Long
'loop through all files in source
sName = Dir(sPath & "*" & sExt)
Do While sName <> ""
fCount = fCount + 1
'we have sName. Now figure out dName
dName = Left(sName, InStrRev(sName, ".") - 1) & dExt
Set AcroXApp = CreateObject("AcroExch.App")
'AcroXApp.Show
Set AcroXAVDoc = CreateObject("AcroExch.AVDoc")
AcroXAVDoc.Open sName, "Acrobat"
Set AcroXPDDoc = AcroXAVDoc.GetPDDoc
Set jsObj = AcroXPDDoc.GetJSObject
jsObj.SaveAs dName, "com.adobe.acrobat.plain-text"
'find the next file
sName = Dir
Loop
AcroXAVDoc.Close False
AcroXApp.Hide
AcroXApp.Exit
MsgBox "Found " & fCount & " files."
End Sub
If you do NOT have Acrobat installed, you can try the script below
Sub ConvertToTXT()
Dim file As Variant, wdDoc As Document
file = Dir("C:\your_path\" & "*.pdf") 'txt path
Do While (file <> "")
Set wdDoc = Documents.Open(Filename:="C:\your_path\" & file, ReadOnly:=True, _
AddToRecentFiles:=False, Format:=wdOpenFormatAuto, Visible:=False)
wdDoc.SaveAs2 Filename:="C:\your_path\" & Replace(file, ".pdf", ".txt"), _
FileFormat:=wdFormatPDF, AddToRecentFiles:=False
wdDoc.Close False
file = Dir
Loop
End Sub
I need to generate many .xls files
renamed as the name contained in row A1, A2, A3 ....
example: NAME1.xls, NAME2.xls ...
and the new generated file must contain only the cells contained in the markers ####
(see IMG...cellD4:T32)
the markers change manually entered by me.
I tried this code only to save new .xls files
but it does not work....I do not know how to do the rest
Private Sub CommandButton1_Clickl()
Dim path As String
Dim filename1 As String
path = "C:\"
filename1 = Range("A1").Text
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=path & filename1 & ".xls", FileFormat:=x1OpenXMLWorkbook
Application.DisplayAlerts = True
ActiveWorkbook.Close
End Sub
Okay here ya go. This should grab the chunk of the original workbook you're looking for and save it as multiple new workbooks.
Option 1 removes formatting
Private Sub CommandButton1_Clickl()
Dim wksht As Worksheet
Set wksht = ActiveSheet
Dim path As String
path = "C:\test\"
If Len(Dir(path, vbDirectory)) = 0 Then
MkDir path
End If
Dim arr() As Variant
arr = wksht.Range("C3:U33").value
Dim wb As Workbook
Dim i As Long
For i = 1 To ActiveSheet.Range("A1").End(xlDown).Row
Set wb = Application.Workbooks.Add
wb.Sheets(1).Range("A1", Cells(UBound(arr), UBound(arr, 2))).value = arr
wb.SaveAs filename:=path & wksht.Range("A" & i).value & ".xlsx"
wb.Close
Next i
End Sub
Option 2 keeps formatting
Private Sub CommandButton1_Clickl()
Dim wksht As Worksheet
Set wksht = ActiveSheet
Dim path As String
path = "C:\test\"
If Len(Dir(path, vbDirectory)) = 0 Then
MkDir path
End If
Dim dataRange As Range
Set dataRange = wksht.Range("C3", wksht.UsedRange.SpecialCells(xlCellTypeLastCell))
Dim wb As Workbook
Dim i As Long
For i = 1 To wksht.Range("A" & wksht.rows.count).End(xlUp).Row
Set wb = Application.Workbooks.Add
dataRange.Copy wb.Sheets(1).Range("A1", wb.Sheets(1).Cells(dataRange.rows.count, dataRange.Columns.count))
wb.SaveAs filename:=path & wksht.Range("A" & i).value & ".xlsx"
wb.Close
Next i
End Sub
but note that the starting point is still C3 based on the example given.
Option 3 keeps formatting and selects the range between the 2 cells with #### in them
Private Sub CommandButton1_Clickl()
Dim wksht As Worksheet
Set wksht = ActiveSheet
Dim path As String
path = "C:\test\"
If Len(Dir(path, vbDirectory)) = 0 Then
MkDir path
End If
Dim rngeStart
Dim rngeEnd
Set rngeStart = wksht.UsedRange.Find(What:="####", LookIn:=xlValues, LookAt:=xlWhole)
Set rngeEnd = wksht.UsedRange.FindNext(After:=rngeStart)
Dim dataRange As Range
Set dataRange = wksht.Range(rngeStart, rngeEnd)
Dim wb As Workbook
Dim i As Long
For i = 1 To wksht.Range("A" & wksht.rows.count).End(xlUp).Row
Set wb = Application.Workbooks.Add
dataRange.Copy wb.Sheets(1).Range("A1", wb.Sheets(1).Cells(dataRange.rows.count, dataRange.Columns.count))
wb.SaveAs filename:=path & wksht.Range("A" & i).value & ".xlsx"
wb.Close
Next i
End Sub
Option 5 keeps row heights and column widths
Private Sub CommandButton1_Clickl()
Dim wksht As Worksheet
Set wksht = ActiveSheet
Dim path As String
path = "C:\test\"
If Len(Dir(path, vbDirectory)) = 0 Then
MkDir path
End If
Dim rngeStart
Dim rngeEnd
Set rngeStart = wksht.UsedRange.Find(What:="####", LookIn:=xlValues, LookAt:=xlWhole)
Set rngeEnd = wksht.UsedRange.FindNext(After:=rngeStart)
Dim dataRange As Range
Set dataRange = wksht.Range(rngeStart, rngeEnd)
Dim newDataRange As Range
Dim wb As Workbook
Dim i As Long
Dim j As Long
Dim k As Long
For i = 1 To wksht.Range("A" & wksht.Rows.Count).End(xlUp).Row
Set wb = Application.Workbooks.Add
Set newDataRange = wb.Sheets(1).Range("A1", wb.Sheets(1).Cells(dataRange.Rows.Count, dataRange.Columns.Count))
dataRange.Copy newDataRange
For j = 1 To dataRange.Columns.Count
newDataRange.Cells(1, j).ColumnWidth = dataRange.Cells(1, j).ColumnWidth
Next j
For k = 1 To dataRange.Rows.Count
newDataRange.Cells(k, 1).RowHeight = dataRange.Cells(k, 1).RowHeight
Next k
wb.SaveAs filename:=path & wksht.Range("A" & i).Value & ".xlsx"
wb.Close
Next i
End Sub
Try this:
Sub filename()
Dim i As Integer
For i = 1 To 32
ChDir "C:\path\"
ActiveWorkbook.SaveAs Filename:= _
"C:\path\" & Range("A" & i).Value & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Next i
End Sub
Note: Don't use "C:\" choose another folder. Probably you will need admin permissions to save there.
I have a folder with 111 excel work books. I want to copy and paste every file into one excel file into separate sheets. So one sheet should have the contents of one file. Each file contains only one sheet. Any ideas would help as i am not very familiar with VBA. And I don't want to copy and paste 111 times.
Thanks.
I had the same issue recently. This code is all you need. Specify a folder and it will combine all workbooks into one (handles them even if they have multiple sheets, too).
' found at: http://www.vbaexpress.com/kb/getarticle.php?kb_id=829
Option Explicit
'32-bit API declarations
Declare Function SHGetPathFromIDList Lib "shell32.dll" _
Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal _
pszpath As String) As Long
Declare Function SHBrowseForFolder Lib "shell32.dll" _
Alias "SHBrowseForFolderA" (lpBrowseInfo As BrowseInfo) _
As Long
Public Type BrowseInfo
hOwner As Long
pIDLRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type
Function GetDirectory(Optional msg) As String
On Error Resume Next
Dim bInfo As BrowseInfo
Dim path As String
Dim r As Long, x As Long, pos As Integer
'Root folder = Desktop
bInfo.pIDLRoot = 0&
'Title in the dialog
If IsMissing(msg) Then
bInfo.lpszTitle = "Please select the folder of the excel files to copy."
Else
bInfo.lpszTitle = msg
End If
'Type of directory to return
bInfo.ulFlags = &H1
'Display the dialog
x = SHBrowseForFolder(bInfo)
'Parse the result
path = Space$(512)
r = SHGetPathFromIDList(ByVal x, ByVal path)
If r Then
pos = InStr(path, Chr$(0))
GetDirectory = Left(path, pos - 1)
Else
GetDirectory = ""
End If
End Function
Sub CombineFiles()
Dim path As String
Dim FileName As String
Dim LastCell As range
Dim Wkb As Workbook
Dim ws As Worksheet
Dim ThisWB As String
ThisWB = ThisWorkbook.Name
Application.EnableEvents = False
Application.ScreenUpdating = False
path = GetDirectory
FileName = Dir(path & "\*.xls", vbNormal)
Do Until FileName = ""
If FileName <> ThisWB Then
Set Wkb = Workbooks.Open(FileName:=path & "\" & FileName)
For Each ws In Wkb.Worksheets
Set LastCell = ws.cells.SpecialCells(xlCellTypeLastCell)
If LastCell.Value = "" And LastCell.Address = range("$A$1").Address Then
Else
ws.Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.count)
End If
Next ws
Wkb.Close False
End If
FileName = Dir()
Loop
Application.EnableEvents = True
Application.ScreenUpdating = True
Set Wkb = Nothing
Set LastCell = Nothing
End Sub
This is a shorter version. You'll need to do Tools/References and add Microsoft Scripting Runtime.
Sub CopySheet1s()
' Copies first sheet from all workbooks in current path
' to a new workbook called wbOutput.xlsx
Dim fso As New Scripting.FileSystemObject
Dim vFile As Variant, sFile As String, lPos As Long
Dim wbInput As Workbook, wbOutput As Workbook
Dim fFolder As Folder
Const cOUTPUT As String = "wbOutput.xlsx"
If fso.FileExists(cOUTPUT) Then
fso.DeleteFile cOUTPUT
End If
Set wbOutput = Workbooks.Add()
Set fFolder = fso.GetFolder(ThisWorkbook.Path)
For Each vFile In fFolder.Files
lPos = InStrRev(vFile, "\")
sFile = Mid(vFile, lPos + 1)
If sFile <> cOUTPUT And sFile <> ThisWorkbook.Name And Left(sFile, 1) <> "~" Then
Set wbInput = Workbooks.Open(Filename:=sFile, ReadOnly:=True)
wbInput.Worksheets(1).Copy after:=wbOutput.Worksheets(1)
wbInput.Close savechanges:=False
End If
Next
wbOutput.SaveAs Filename:=cOUTPUT
wbOutput.Close
End Sub
Place all your .xls files into one folder, enter the files path in 'Enter Files Path Here' and run the macro.
Sub GetSheets()
Path = "C:\Enter Files Path Here\"
Filename = Dir(Path & "*.xls")
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub