I am very new to VBA. I keep on getting an error of type mismatch whenever the cancel/quit button in the dialogue box is clicked. The error appears on the Application.GetOpenFileName line. Does anyone know what is wrong here? I have tried several methods but none of them work :(
Thanks!
Here's my code:
Private Sub cmdBrowse_Click()
Application.ScreenUpdating = False
Dim i As Long, j As Long, iCheck As Long
Dim fname() As Variant
Dim wkbNameList As String, wkbNamePath As String
Dim win As Window
fname = Application.GetOpenFilename(filefilter:="Excel, *xlsx; *xlsm", MultiSelect:=True)
If fname = "False" Then
Exit Sub
End If
For i = LBound(fname) To UBound(fname)
workbooks.Open Filename:=fname(i)
wkbNameList = wkbNameList & workbooks(i + 1).Name & vbCrLf
wkbNamePath = wkbNamePath & fname(i) & " , "
Next i
function returns an array when files are selected, but returns a string when cancel/quit is selected
try this
Private Sub cmdBrowse_Click()
Application.ScreenUpdating = False
Dim i As Long, j As Long, iCheck As Long
Dim fname As Variant
Dim wkbNameList As String, wkbNamePath As String
Dim win As Window
fname = Application.GetOpenFilename(filefilter:="Excel, *xlsx; *xlsm", MultiSelect:=True)
If IsArray(fname) Then 'file selected
For i = LBound(fname) To UBound(fname)
Workbooks.Open Filename:=fname(i)
wkbNameList = wkbNameList & Workbooks(i + 1).Name & vbCrLf
wkbNamePath = wkbNamePath & fname(i) & " , "
Next i
ElseIf fname = "False" Then 'cancel/quit
Exit Sub
End If
End Sub
As pointed out by Kostas K. in the comments on h2so4's reply, the method returns boolean (False) when the dialog is cancelled, and array when a file is chosen.
I'd suggest trying this slight modification of h2so4's code:
Private Sub cmdBrowse_Click()
Application.ScreenUpdating = False
Dim i As Long, j As Long, iCheck As Long
Dim fname() As Variant
Dim wkbNameList As String, wkbNamePath As String
Dim win As Window
fname = Application.GetOpenFilename(filefilter:="Excel, *xlsx; *xlsm", MultiSelect:=True)
'the only option to get boolean is to have cancelled the dialog, which gives False for the variable
If VarType(fname) = vbBoolean Then
Exit Sub
Else
For i = LBound(fname) To UBound(fname)
workbooks.Open Filename:=fname(i)
wkbNameList = wkbNameList & workbooks(i + 1).Name & vbCrLf
wkbNamePath = wkbNamePath & fname(i) & " , "
Next i
End If
End Sub
'I ran into this problem working with multiselect as well
'Something like this will work
'The problem is [cancel] returns a Boolean instead of an array.. so we make it return an array
Dim fname(), fname_catcherror() As Variant
fname_catcherror = Array(Application.GetOpenFilename(filefilter:="Excel, *xlsx; *xlsm", MultiSelect:=True), True)
if VarType(fname_catcherror(0)) <> vbBoolean Then
fname = fname_catcherror(0)
'..code here
end if
Related
I am developing a user form as you can see below
enter image description here
the code in the Browse Button is
Private Sub Browse_Click()
Dim fName As String
fName = Application.GetOpenFilename("CSV File (*.csv), *.csv", , "Import .CSV File", , False)
If Not fName = "False" Then
TextBox1.Value = fName
End If
End Sub
Next step is to choose some of these options and the code behind it is
Private Sub Start_Click()
Dim Actsheet As String
Dim wkbCrntWorkBook As Workbook
Dim wkbSourceBook As Workbook
Dim rngSourceRange As Range
Dim rngDestination As Range
Set wkbCrntWorkBook = ActiveWorkbook
Set rngDestination = wkbCrntWorkBook.ActiveSheet.Range("A1:A1")
If myBeforeImprovements = True Then
Actsheet = "Before "
ElseIf AfterImprovements = True Then
Actsheet = "After "
Else
MsgBox ("Select Type of Analysis")
Exit Sub
End If
If Westbound = True Then
Actsheet = Actsheet & "WB"
ElseIf Northbound = True Then
Actsheet = Actsheet & "NB"
ElseIf Eastbound = True Then
Actsheet = Actsheet & "EB"
ElseIf Southbound = True Then
Actsheet = Actsheet & "SB"
Else
MsgBox ("Select Traffic Bound")
Exit Sub
End If
my problem is I can't take the CSV file to its write sheet which are
Before EB
Before WB
Before NB
Before SB
After EB
After WB
After NB
After SB
maybe the following code will refer to the selected CSV file but it gives me an error
Workbooks.OpenText Filename:=TextBox1.Text + "," + ComboBox1.Value + ".txt", _
DataType:=xlDelimited, Tab:=True
Replace + with & and it'll hopefully work better. The concatenation operator is & in VBA
I have below code which prints text from a column but open a text file many times instead of once. Please let me know what is the wrong.
When I run sub in Visual Basic debug mode, it open text file only once. But I am calling this macro after another macro and that time it is opening (same) text file many times.
Sub createdevtest()
Dim filename As String, lineText As String
Dim data As Range
Dim myrng As Range, i, j
' filename = ThisWorkbook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"
filename = ThisWorkbook.Path & "\devtest" & ".txt"
Open filename For Output As #1
Dim LastRow As Long
'Find the last non-blank cell in column A(1)
LastRow = Cells(Rows.count, 1).End(xlUp).Row
Range("B4:B" & LastRow).Select
Set myrng = Selection
For i = 1 To myrng.Rows.count
For j = 1 To myrng.Columns.count
lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
Next j
Print #1, lineText
Next i
Close #1
Range("B4").Select
' open devtest
'Shell "explorer.exe" & " " & ThisWorkbook.Path, vbNormalFocus
filename = Shell("Notepad.exe " & filename, vbNormalFocus)
End Sub
Thanks #Luuklag. I had tried to figure out on my own but no success. After your comment, just went thru code again and got clue.
Below is the correct code where I have called one of the macro (devtest1) which contains above text file creation macro (createdevtest). Before correction I was calling macro in function instead of Sub, so it was looping again and opening txt file many times.
' macro to select folder and list files
Sub GetFileNames_devtest()
Set Folder = Application.FileDialog(msoFileDialogFolderPicker)
If Folder.Show <> -1 Then Exit Sub
xDir = Folder.SelectedItems(1)
Call ListFilesInFolder(xDir, True)
' call devtest: corrected to call macro at right place
devtest1
End Sub
Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean)
Dim xFileSystemObject As Object
Dim xFolder As Object
Dim xSubFolder As Object
Dim xFile As Object
Dim rowIndex As Long
Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
Set xFolder = xFileSystemObject.GetFolder(xFolderName)
rowIndex = Application.ActiveSheet.Range("A65536").End(xlUp).Row + 1
For Each xFile In xFolder.Files
Application.ActiveSheet.Cells(rowIndex, 1).Formula = xFile.Name
rowIndex = rowIndex + 1
Next xFile
If xIsSubfolders Then
For Each xSubFolder In xFolder.SubFolders
ListFilesInFolder xSubFolder.Path, True
Next xSubFolder
End If
Set xFile = Nothing
Set xFolder = Nothing
Set xFileSystemObject = Nothing
'' Was calling wrongly macro here
End Sub
Function GetFileOwner(ByVal xPath As String, ByVal xName As String)
Dim xFolder As Object
Dim xFolderItem As Object
Dim xShell As Object
xName = StrConv(xName, vbUnicode)
xPath = StrConv(xPath, vbUnicode)
Set xShell = CreateObject("Shell.Application")
Set xFolder = xShell.Namespace(StrConv(xPath, vbFromUnicode))
If Not xFolder Is Nothing Then
Set xFolderItem = xFolder.ParseName(StrConv(xName, vbFromUnicode))
End If
If Not xFolderItem Is Nothing Then
GetFileOwner = xFolder.GetDetailsOf(xFolderItem, 8)
Else
GetFileOwner = ""
End If
Set xShell = Nothing
Set xFolder = Nothing
Set xFolderItem = Nothing
End Function
End Function
I was working with a vba and I'm trying to open all excel files in a folder (about 8-10) based on cell values. I was wondering if this is the right approach to opening it, it keeps giving me syntax error where I wrote the directory. and when I rewrote that section, the vba only shot out the msgbox which meant it had to have looped and did something right? but didn't open any files. Any information will help. Thank you guys so much for taking the time to help me in any way.
Sub OpenFiles()
Dim search As Worksheet
Dim customer As Range
Dim customerfolder As Range
Dim QualityHUB As Workbook
'setting variable references
Set QualityHUB = ThisWorkbook
Set search = Worksheets("Search")
Set customer = Worksheets("Search").Range("$D$1")
Set customerfolder = Worksheets("Search").Range("$D$3")
With QualityHUB
If IsEmpty((customer)) And IsEmpty((customerfolder)) Then
MsgBox "Please Fill out Customer Information and search again"
Exit Sub
End If
End With
With QualityHUB
Dim MyFolder As String
Dim MyFile As String
Dim Directory As String
Directory = "O:\LAYOUT DATA\" & customer & "\" & customerfolder"
MyFile = Dir(Directory & "*.xlsx")
Do While MyFile <> ""
Workbooks.Open Filename:=MyFile
MyFile = Dir()
Loop
MsgBox "Files Open for " + customerfolder + " complete"
End With
End Sub
This worked for me perfectly
Sub OpenFiles()
Dim search As Worksheet
Dim customer As Range
Dim customerfolder As Range
Dim QualityHUB As Workbook
'setting variable references
Set QualityHUB = ThisWorkbook
Set search = Worksheets("Search")
Set customer = Worksheets("Search").Range("$D$1")
Set customerfolder = Worksheets("Search").Range("$D$3")
With QualityHUB
If IsEmpty((customer)) And IsEmpty((customerfolder)) Then
MsgBox "Please Fill out Customer Information and search again"
Exit Sub
End If
End With
With QualityHUB
Dim MyFolder As String
Dim MyFile As String
Dim Directory As String
Directory = "O:\LAYOUT DATA\" & customer & "\" & customerfolder & "\"
MyFile = Dir(Directory & "*.xlsx")
Do While MyFile <> ""
Workbooks.Open Filename:=Directory & MyFile
MyFile = Dir()
Loop
MsgBox "Files Open for " + customerfolder + " complete"
End With
End Sub
one of the issue was, you had to write
Workbooks.Open Filename:=Directory & MyFile
instead of
Workbooks.Open Filename:=MyFile
Corrected some issues with your code and cleaned it up, give this a try. I think the big issue was you had an extra double-quote, and you missing the ending \ in the Directory line:
Sub OpenFiles()
Dim QualityHUB As Workbook
Dim search As Worksheet
Dim customer As String
Dim customerfolder As String
Dim Directory As String
Dim MyFile As String
'setting variable references
Set QualityHUB = ThisWorkbook
Set search = QualityHUB.Worksheets("Search")
customer = search.Range("$D$1").Value
customerfolder = search.Range("$D$3").Value
If Len(Trim(customer)) = 0 Or Len(Trim(customerfolder)) = 0 Then
MsgBox "Please Fill out Customer Information and search again"
Exit Sub
End If
Directory = "O:\LAYOUT DATA\" & customer & "\" & customerfolder & "\" '<--- This requires the ending \
MyFile = Dir(Directory & "*.xlsx")
Do While Len(MyFile) > 0
Workbooks.Open Filename:=Directory & MyFile
MyFile = Dir()
Loop
MsgBox "Files Open for " + customerfolder + " complete"
End Sub
I found this code online and it will open all the excel files in a folder, you can adapt the code to apply a function to the workbook, once it is open.
Option Explicit
Type FoundFileInfo
sPath As String
sName As String
End Type
Sub find()
Dim iFilesNum As Integer
Dim iCount As Integer
Dim recMyFiles() As FoundFileInfo
Dim blFilesFound As Boolean
blFilesFound = FindFiles("G:\LOCATION OF FOLDER HERE\", _
recMyFiles, iFilesNum, "*.xlsx", True)
End Sub
Function FindFiles(ByVal sPath As String, _
ByRef recFoundFiles() As FoundFileInfo, _
ByRef iFilesFound As Integer, _
Optional ByVal sFileSpec As String = "*.*", _
Optional ByVal blIncludeSubFolders As Boolean = False) As Boolean
Dim iCount As Integer '* Multipurpose counter
Dim sFileName As String '* Found file name
Dim wbResults, file, WS_Count, i, gcell, col, finRow, wbCodeBook As Workbook, lCount, name, looper
Dim WorksheetExists
Set wbCodeBook = ThisWorkbook
'*
'* FileSystem objects
Dim oFileSystem As Object, _
oParentFolder As Object, _
oFolder As Object, _
oFile As Object
Set oFileSystem = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set oParentFolder = oFileSystem.GetFolder(sPath)
If oParentFolder Is Nothing Then
FindFiles = False
On Error GoTo 0
Set oParentFolder = Nothing
Set oFileSystem = Nothing
Exit Function
End If
sPath = IIf(Right(sPath, 1) = "\", sPath, sPath & "\")
'*
'* Find files
sFileName = Dir(sPath & sFileSpec, vbNormal)
If sFileName <> "" Then
For Each oFile In oParentFolder.Files
If LCase(oFile.name) Like LCase(sFileSpec) Then
iCount = UBound(recFoundFiles)
iCount = iCount + 1
ReDim Preserve recFoundFiles(1 To iCount)
file = sPath & oFile.name
name = oFile.name
End If
On Error GoTo nextfile:
Set wbResults = Workbooks.Open(Filename:=file, UpdateLinks:=0)
''insert your code here
wbResults.Close SaveChanges:=False
nextfile:
Next oFile
Set oFile = Nothing '* Although it is nothing
End If
If blIncludeSubFolders Then
'*
'* Select next sub-forbers
For Each oFolder In oParentFolder.SubFolders
FindFiles oFolder.path, recFoundFiles, iFilesFound, sFileSpec, blIncludeSubFolders
Next
End If
FindFiles = UBound(recFoundFiles) > 0
iFilesFound = UBound(recFoundFiles)
On Error GoTo 0
'*
'* Clean-up
Set oFolder = Nothing '* Although it is nothing
Set oParentFolder = Nothing
Set oFileSystem = Nothing
End Function
Function SSCGetColumnCodeFromIndex(colIndex As Variant) As String
Dim tstr As String
Dim prefixInt As Integer
Dim suffixInt As Integer
prefixInt = Int(colIndex / 26)
suffixInt = colIndex Mod 26
If prefixInt = 0 Then
tstr = ""
Else
prefixInt = prefixInt - 1
tstr = Chr(65 + prefixInt)
End If
tstr = tstr + Chr(65 + suffixInt)
SSCGetColumnCodeFromIndex = tstr
End Function
Function GetColNum(oSheet As Worksheet, name As String)
Dim Endrow_Col, i
'For loop to get the column number of name
Endrow_Col = oSheet.Range("A1").End(xlToRight).Column
oSheet.Select
oSheet.Range("A1").Select
For i = 0 To Endrow_Col - 1 Step 1
If ActiveCell.Value <> name Then
ActiveCell.Offset(0, 1).Select
ElseIf ActiveCell.Value = name Then
GetColNum = ActiveCell.Column
Exit For
End If
Next i
End Function
Function ShDel(name As String)
End If
End Function
Does anyone have an idea how to return parameter name in VBA?
This is what I have:
Sub Main()
Dim MyString As String
MyString = "Hello World"
MsgBox MyString
End Sub
It shows only "Hello World". I would like to have it "MyString says Hello World", but dynamically, not by entering
MsgBox "MyString says " & MyString
I would prefer something like
MsgBox ParamName(MyString) & " says " & MyString
but it actually won't work... Could anyone help?
I believe I have accomplished what you are looking to do here. However, please note that this will currently only work for your first parameter in a macro assigned to a Form control:
Step 1
Add the following code, adapted from here, to a new Module:
Public Function ExportModules(ModuleName As String) As String
Dim bExport As Boolean
Dim wkbSource As Excel.Workbook
Dim szSourceWorkbook As String
Dim szExportPath As String
Dim szFileName As String
Dim cmpComponent As VBIDE.VBComponent
''' The code modules will be exported in a folder named.
''' VBAProjectFiles in the Documents folder.
''' The code below create this folder if it not exist
''' or delete all files in the folder if it exist.
If FolderWithVBAProjectFiles = "Error" Then
MsgBox "Export Folder not exist"
Exit Function
End If
On Error Resume Next
Kill FolderWithVBAProjectFiles & "\*.*"
On Error GoTo 0
''' NOTE: This workbook must be open in Excel.
szSourceWorkbook = ActiveWorkbook.Name
Set wkbSource = Application.Workbooks(szSourceWorkbook)
If wkbSource.VBProject.Protection = 1 Then
MsgBox "The VBA in this workbook is protected," & _
"not possible to export the code"
Exit Function
End If
szExportPath = FolderWithVBAProjectFiles & "\"
Set cmpComponent = wkbSource.VBProject.VBComponents(ModuleName)
bExport = True
szFileName = cmpComponent.Name
''' Concatenate the correct filename for export.
Select Case cmpComponent.Type
Case vbext_ct_ClassModule
szFileName = szFileName & ".cls"
Case vbext_ct_MSForm
szFileName = szFileName & ".frm"
Case vbext_ct_StdModule
szFileName = szFileName & ".bas"
Case vbext_ct_Document
''' This is a worksheet or workbook object.
''' Don't try to export.
bExport = False
End Select
If bExport Then
''' Export the component to a text file.
cmpComponent.Export szExportPath & szFileName
''' remove it from the project if you want
'''wkbSource.VBProject.VBComponents.Remove cmpComponent
End If
ExportModules = szExportPath & szFileName
End Function
Function FolderWithVBAProjectFiles() As String
Dim WshShell As Object
Dim FSO As Object
Dim SpecialPath As String
Set WshShell = CreateObject("WScript.Shell")
Set FSO = CreateObject("scripting.filesystemobject")
SpecialPath = WshShell.SpecialFolders("MyDocuments")
If Right(SpecialPath, 1) <> "\" Then
SpecialPath = SpecialPath & "\"
End If
If FSO.FolderExists(SpecialPath & "VBAProjectFiles") = False Then
On Error Resume Next
MkDir SpecialPath & "VBAProjectFiles"
On Error GoTo 0
End If
If FSO.FolderExists(SpecialPath & "VBAProjectFiles") = True Then
FolderWithVBAProjectFiles = SpecialPath & "VBAProjectFiles"
Else
FolderWithVBAProjectFiles = "Error"
End If
End Function
Step 2
Add the following code, adapted from answer #7 here, and from here, along with my own function, to a new module (it could be the same module as the first if preferred):
Public Function MyMacroInfo() As String
Dim MacroName$, SubName$, ModArr As Variant
Dim ModName As Object, strModName$, i&, j&
MacroName = ActiveSheet.Buttons(Application.Caller).OnAction
SubName = Application.Replace(MacroName, 1, Application.Search("!", MacroName), "")
ModArr = Array(0, 1, 2, 3)
For Each ModName In ActiveWorkbook.VBProject.VBComponents
For j = LBound(ModArr) To UBound(ModArr)
i = 0
On Error Resume Next
i = ModName.CodeModule.ProcStartLine(SubName, CLng(ModArr(j)))
Err.Clear
If i > 0 Then
strModName = ModName.Name
Exit For
End If
Next j
Next ModName
MyMacroInfo = strModName
End Function
Public Function GetParamName(ModulePath As String) As String
Dim text As String
Dim textline As String
Dim ParamStartLocation As Long
Dim ParamEndLocation As Long
Dim ParamLength As Long
Dim i As Long
Open ModulePath For Input As #1
Do Until EOF(1)
Line Input #1, textline
text = text & textline
Loop
Close #1
ParamStartLocation = 0
For i = 1 To 3
ParamStartLocation = InStr(ParamStartLocation + 1, text, "Dim ")
Next i
ParamEndLocation = InStr(ParamStartLocation, text, " As ")
ParamLength = ParamEndLocation - ParamStartLocation
GetParamName = Left(Right(text, Len(text) - ParamStartLocation - 3), ParamLength - 4)
End Function
Step 3
Change your sub to the following:
Sub Main()
'--------Leave this section at the top of your sub---------
Dim strExportedModule As String
Dim strParamName As String
strExportedModule = ExportModules(MyMacroInfo)
strParamName = GetParamName(strExportedModule)
'-----------------Start your code here---------------------
Dim MyString As String
MyString = "Hello World"
MsgBox strParamName & " says " & MyString
End Sub
Step 4
Assign Main to a Form Button.
Notes
As noted above, this will only get the first parameter that you dimension in the macro assigned to the Form Button. If this is not acceptable, I'll have to take a look at it to see if it can be modified to meet your needs.
As Ron de Bruin notes on his site, you'll need to do the following:
In the VBE Editor set a reference to "Microsoft Visual Basic For
Applications Extensibility 5.3" and to "Microsoft Scripting Runtime"
and then save the file.
This code will export the module to a folder named "VBAProjectFiles" in your My Documents folder. If you happen to have a folder saved there with the same name (as unlikely as that is), it will delete all the files in that folder.
I'm trying to open all appropriate PDFs found in the same directory as my Excel workbook using VBA. I've added the Adobe Acrobat xx.x Type Library reference to the project. But when I try to create the .App object I get a "Run-time error '429':" error.
What am I missing?
Here's the code;
Sub ImportNames()
Dim BlrInfoFileList() As String, NbrOfFiles As Integer, FileNameStr As String
Dim X As Integer, pdfApp As AcroApp, pdfDoc As AcroAVDoc
'Find all of the Contact Information PDFs
FileNameStr = Dir(ThisWorkbook.Path & "\*Contact Information.pdf")
NbrOfFiles = 0
Do Until FileNameStr = ""
NbrOfFiles = NbrOfFiles + 1
ReDim Preserve BlrInfoFileList(NbrOfFiles)
BlrInfoFileList(NbrOfFiles) = FileNameStr
FileNameStr = Dir()
Loop
For X = 1 To NbrOfFiles
FileNameStr = ThisWorkbook.Path & "\" & BlrInfoFileList(X)
Set pdfApp = CreateObject("AcroExch.App")
pdfApp.Hide
Set pdfDoc = CreateObject("AcroExch.AVDoc")
pdfDoc.Open FileNameStr, vbNormalFocus
SendKeys ("^a")
SendKeys ("^c")
SendKeys "%{F4}"
ThisWorkbook.Sheets("Raw Data").Range("A1").Select
SendKeys ("^v")
Set pdfApp = Nothing
Set pdfDoc = Nothing
'Process Raw Data and Clear the sheet for the next PDF Document
Next X
End Sub
If it's a matter of just opening PDF to send some keys to it then why not try this
Sub Sample()
ActiveWorkbook.FollowHyperlink "C:\MyFile.pdf"
End Sub
I am assuming that you have some pdf reader installed.
Use Shell "program file path file path you want to open".
Example:
Shell "c:\windows\system32\mspaint.exe c:users\admin\x.jpg"
Hope this helps. I was able to open pdf files from all subfolders of a folder and copy content to the macro enabled workbook using shell as recommended above.Please see below the code .
Sub ConsolidateWorkbooksLTD()
Dim adobeReaderPath As String
Dim pathAndFileName As String
Dim shellPathName As String
Dim fso, subFldr, subFlodr
Dim FolderPath
Dim Filename As String
Dim Sheet As Worksheet
Dim ws As Worksheet
Dim HK As String
Dim s As String
Dim J As String
Dim diaFolder As FileDialog
Dim mFolder As String
Dim Basebk As Workbook
Dim Actbk As Workbook
Application.ScreenUpdating = False
Set Basebk = ThisWorkbook
' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
MsgBox diaFolder.SelectedItems(1) & "\"
mFolder = diaFolder.SelectedItems(1) & "\"
Set diaFolder = Nothing
Set fso = CreateObject("Scripting.FileSystemObject")
Set FolderPath = fso.GetFolder(mFolder)
For Each subFldr In FolderPath.SubFolders
subFlodr = subFldr & "\"
Filename = Dir(subFldr & "\*.csv*")
Do While Len(Filename) > 0
J = Filename
J = Left(J, Len(J) - 4) & ".pdf"
Workbooks.Open Filename:=subFldr & "\" & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Set Actbk = ActiveWorkbook
s = ActiveWorkbook.Name
HK = Left(s, Len(s) - 4)
If InStrRev(HK, "_S") <> 0 Then
HK = Right(HK, Len(HK) - InStrRev(HK, "_S"))
Else
HK = Right(HK, Len(HK) - InStrRev(HK, "_L"))
End If
Sheet.Copy After:=ThisWorkbook.Sheets(1)
ActiveSheet.Name = HK
' Open pdf file to copy SIC Decsription
pathAndFileName = subFlodr & J
adobeReaderPath = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"
shellPathName = adobeReaderPath & " """ & pathAndFileName & """"
Call Shell( _
pathname:=shellPathName, _
windowstyle:=vbNormalFocus)
Application.Wait Now + TimeValue("0:00:2")
SendKeys "%vpc"
SendKeys "^a", True
Application.Wait Now + TimeValue("00:00:2")
' send key to copy
SendKeys "^c"
' wait 2 secs
Application.Wait Now + TimeValue("00:00:2")
' activate this workook and paste the data
ThisWorkbook.Activate
Set ws = ThisWorkbook.Sheets(HK)
Range("O1:O5").Select
ws.Paste
Application.Wait Now + TimeValue("00:00:3")
Application.CutCopyMode = False
Application.Wait Now + TimeValue("00:00:3")
Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)
' send key to close pdf file
SendKeys "^q"
Application.Wait Now + TimeValue("00:00:3")
Next Sheet
Workbooks(Filename).Close SaveAs = True
Filename = Dir()
Loop
Next
Application.ScreenUpdating = True
End Sub
I wrote the piece of code to copy from pdf and csv to the macro enabled workbook and you may need to fine tune as per your requirement
Regards,
Hema Kasturi
WOW...
In appreciation, I add a bit of code that I use to find the path to ADOBE
Private Declare Function FindExecutable Lib "shell32.dll" Alias "FindExecutableA" _
(ByVal lpFile As String, _
ByVal lpDirectory As String, _
ByVal lpResult As String) As Long
and call this to find the applicable program name
Public Function GetFileAssociation(ByVal sFilepath As String) As String
Dim i As Long
Dim E As String
GetFileAssociation = "File not found!"
If Dir(sFilepath) = vbNullString Or sFilepath = vbNullString Then Exit Function
GetFileAssociation = "No association found!"
E = String(260, Chr(0))
i = FindExecutable(sFilepath, vbNullString, E)
If i > 32 Then GetFileAssociation = Left(E, InStr(E, Chr(0)) - 1)
End Function
Thank you for your code, which isn't EXACTLY what I wanted, but can be adapted for me.
Here is a simplified version of this script to copy a pdf into a XL file.
Sub CopyOnePDFtoExcel()
Dim ws As Worksheet
Dim PDF_path As String
PDF_path = "C:\Users\...\Documents\This-File.pdf"
'open the pdf file
ActiveWorkbook.FollowHyperlink PDF_path
SendKeys "^a", True
SendKeys "^c"
Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)
Application.ScreenUpdating = False
Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Activate
ws.Range("A1").ClearContents
ws.Range("A1").Select
ws.Paste
Application.ScreenUpdating = True
End Sub