Is it possible with VBA Excel to download data from a website without affecting other tasks? What I want to achieve is to be able to press a button and keep working on other tasks. Right now, when I run the code below, I can't perform other tasks or the code will break. Thanks for everyone's help/input!
Public Sub Get_File()
Dim sFiletype As String 'Fund type reference
Dim sFilename As String 'File name (fund type + date of download), if "" then default
Dim sFolder As String 'Folder name (fund type), if "" then default
Dim bReplace As Boolean 'To replace the existing file or not
Dim sURL As String 'The URL to the location to extract information
Dim pURL As String
Dim Cell, Rng As Range
Dim Sheet As Worksheet
Dim oBrowser As InternetExplorer
Set oBrowser = New InternetExplorer
Dim StartTime As Double
Dim SecondsElapsed As Double
StartTime = Timer
'Initialize variables
Set Rng = Range("I2:I15")
Set Sheet = ActiveWorkbook.Sheets("Macro_Button")
For Each Cell In Rng
If Cell <> "" Then
sFiletype = Cell.Value
sFilename = sFiletype & "_" & Format(Date, "mmddyyyy")
sFolder = Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:Z15"), 2, False)
bReplace = True
sURL = "www.preqin.com"
pURL = Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:Z15"), 16, False)
'Download using the desired approach, XMLHTTP / IE
If Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:Z15"), 15, False) = 1 Then
Call Download_Use_IE(oBrowser, sURL, pURL, sFilename, sFolder, bReplace)
Else
Call Download_NoLogin_Use_IE(oBrowser, pURL, sFilename, sFolder, bReplace)
End If
Else: GoTo Exit_Sub
End If
Next
Exit_Sub:
'Close IE
oBrowser.Quit
'Determine how many seconds code took to run
SecondsElapsed = Round(Timer - StartTime, 2)
MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation
End Sub
Private Sub Download_Use_IE(oBrowser As InternetExplorer, _
ByRef sURL As String, _
ByRef pURL As String, _
Optional ByRef sFilename As String = "", _
Optional ByRef sFolder As String = "", _
Optional ByRef bReplace As Boolean = True)
Dim hDoc As HTMLDocument
Dim objInputs As Object
Dim ele As Object
On Error GoTo ErrorHandler
oBrowser.Visible = True
'Navigate to URL
Call oBrowser.navigate(sURL)
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
'Skips log in step if already signed into website
On Error GoTo LoggedIn
'Enter username
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_user_email").Value = "XXX"
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_user_password").Value = "XXX"
'Submit the sign in
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_btnLogin").Click
'Wait for website to load
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
LoggedIn:
'Initial data export
oBrowser.navigate (pURL)
'Wait for website to load
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
'Set the htmldocument
Set hDoc = oBrowser.document
'Loop and click the download file button
Set objInputs = oBrowser.document.getElementsbyTagName("input")
For Each ele In objInputs
If ele.Title Like "Download Data to Excel" Then
ele.Click
End If
Next
'Wait for dialogue box to load
While oBrowser.Busy Or oBrowser.readyState > 3: DoEvents: Wend
Application.Wait (Now + TimeValue("0:00:02"))
'IE 9+ requires to confirm save
Call Download(oBrowser, sFilename, sFolder, bReplace)
Exit Sub
ErrorHandler:
'Resume
Debug.Print "Sub Download_Use_IE() " & Err & ": " & Error(Err)
End Sub
Try the
DoEvents
As far i know, is not easy to work with background process and excel.
Cheers.
You cannot work on the Workbook that is running the macro. You can open another instance of Excel, or a read only copy of the workbook running the macro if you would like to work within Excel while the macro is running. This question has been asked and answered before on here
It is difficult to determine from your question whether you are talking about "other tasks" as in within Excel or just on your computer in general. My above paragraph answers whether you can do tasks within Excel while the macro is running.
Related
I have multiple word documents in a folder.
What I really want is to list the document names and check whether these docs incude some specified words.
I create two word documents for example to explain.
There are two documents, Doc A and Doc B, in a folder.
I want to list the file name Doc A and Doc B in the excel column A.
After listing the doc name in column A, I want to check whether specified words "classification" and "Statistics" are in the docs.
If these specified words in the document, it will mark in the excel. Please see below picture for the result I want.
I provide the code in the following:
Option Explicit
Private xRow As Long
Sub Get_MAIN_File_Names()
Dim fso As FileSystemObject
Dim xDirect As String
Dim xRootFolder As Folder
Dim DrawingNumb As String
Dim RevNumb As String
Dim rootFolderStr As String
Set fso = New FileSystemObject
xRow = 0
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Main File"
.Show
'PROCESS ROOT FOLDER
If .SelectedItems.Count <> 0 Then
xDirect = .SelectedItems(1) & "\"
Set xRootFolder = fso.GetFolder(xDirect)
ProcessFolder fso, xRootFolder
End If
End With
End Sub
Private Sub ProcessFolder(fso As FileSystemObject, xFolder As Folder)
Dim xFiles As Files
Dim xFile As File
Dim xSubFolders As Folders
Dim xSubFolder As Folder
Dim xFileName As String
Dim objWordApplication As New Word.Application
Dim objWordDocument As Word.Document
Dim strFile As String
strFile = Dir(xFolder & "*.doc", vbNormal)
While strFile <> ""
With objWordApplication
Set objWordDocument = .Documents.Open(FileName:=xFolder & strFile, AddToRecentFiles:=False, ReadOnly:=True, Visible:=False)
Set xFiles = xFolder.Files
'Adding Column names
Cells(1, "A").Value = "Document Name"
Cells(1, "B").Value = "classification"
Cells(1, "C").Value = "Statistics"
'LOOPS THROUGH EACH FILE NAME IN FOLDER
For Each xFile In xFiles
'EXTRACT INFORMATION FROM FILE NAME, this part may not add
xFileName = xFile.Name
Set Docs = objWordDocument.Content
With Docs.Find
.ClearFormatting
.Text = "classification"
Wrap:=wdFindContinue
End With
With Docs.Find
.ClearFormatting
.Text = "Statistics"
Wrap:=wdFindContinue
End With
'INSERT INFO INTO EXCEL
ActiveCell.Offset(xRow, 0) = xFileName
'Below needs to add.
ActiveCell.Offset(xRow, 1) =
ActiveCell.Offset(xRow, 2) =
'Above needs to add.
xRow = xRow + 1
With objWordDocument
.Close
End With
Next xFile
Set xSubFolders = xFolder.SubFolders
For Each xSubFolder In xSubFolders
ProcessFolder fso, xSubFolder
Next xSubFolder
End Sub
Based on above code, it fails.
I think the problem is With Docs.Find.....; however, I'm not really sure about it.
Moreover, I do not know how to do this part.
'Below needs to add.
ActiveCell.Offset(xRow, 1) =
ActiveCell.Offset(xRow, 2) =
'Above needs to add.
Can any one help me edit the code?
Maybe this code will help you out, it does:
Assume you got a activesheet setup with the three headers there
Loop through .docx files in specified folder
Checks wordrange for specified tekst
Returns true or false and puts found or not found in appropriate cell
Sub LoopWordDocs()
Dim FLDR As String
Dim wDoc As Word.Document
Dim wRNG As Word.Range
Dim LR As Long, COL As Long
Dim WS As String
Dim wAPP As Word.Application
Dim WordWasNotRunning As Boolean
On Error Resume Next
Set wAPP = GetObject(, "Word.Application")
If Err Then
Set wAPP = New Word.Application
WordWasNotRunning = True
End If
On Error GoTo Err_Handler
WS = ThisWorkbook.ActiveSheet.Name
FLDR = "U:\Test\" 'Change directory accordingly
aDoc = Dir(FLDR & "*.docx") 'Change docx to .doc if you need
Do While aDoc <> ""
Set wDoc = Documents.Open(Filename:=FLDR & aDoc)
LR = Sheets(WS).Cells(Rows.Count, "A").End(xlUp).Row + 1
Sheets(WS).Cells(LR, 1) = aDoc
Set wRNG = wDoc.Range
For COL = 2 To 3 'It will loop through B1 and C1 to check if present in text
With wRNG.Find
.Text = Sheets(WS).Cells(1, COL).Text
.MatchCase = False
.MatchWholeWord = True
If wRNG.Find.Execute = True Then
Sheets(WS).Cells(LR, COL) = "V" 'Change V to your liking
Else
Sheets(WS).Cells(LR, COL) = "X" 'Change X to your liking
End If
End With
Next COL
wDoc.Close SaveChanges:=True
aDoc = Dir
Loop
Exit Sub
Err_Handler:
MsgBox "Word caused a problem. " & Err.Description, vbCritical, "Error: " & Err.Number
If WordWasNotRunning Then
wAPP.Quit
End If
End Sub
Note: You'll have to turn on Microsoft Word 14.0 Object Library for this to work
Im seeking for help as i have a bulk of links to check if the link is broken i have tried the below macro but it works twice and after that it is no longer working i am using ms office 10 64bit i would like to add on the macro if macro
can check the image resolution for example if i paste url on column A it will highlight the broken links and on column b it will show the image resolution
Sub Audit_WorkSheet_For_Broken_Links()
If MsgBox("Is the Active Sheet a Sheet with Hyperlinks You Would Like to Check?", vbOKCancel) = vbCancel Then
Exit Sub
End If
On Error Resume Next
For Each alink In Cells.Hyperlinks
strURL = alink.Address
If Left(strURL, 4) <> "http" Then
strURL = ThisWorkbook.BuiltinDocumentProperties("Hyperlink Base") & strURL
End If
Application.StatusBar = "Testing Link: " & strURL
Set objhttp = CreateObject("MSXML2.XMLHTTP")
objhttp.Open "HEAD", strURL, False
objhttp.Send
If objhttp.statustext <> "OK" Then
alink.Parent.Interior.Color = 255
End If
Next alink
Application.StatusBar = False
On Error GoTo 0
MsgBox ("Checking Complete!" & vbCrLf & vbCrLf & "Cells With Broken or Suspect Links are Highlighted in RED.")
End Sub
Edit: I changed your macro to declare variables properly and release objects upon macro completion; this should address any potential memory issues. Please try this code and let me know if it works.
Sub Audit_WorkSheet_For_Broken_Links()
If MsgBox("Is the Active Sheet a Sheet with Hyperlinks You Would Like to Check?", vbOKCancel) = vbCancel Then
Exit Sub
End If
Dim alink As Hyperlink
Dim strURL As String
Dim objhttp As Object
On Error Resume Next
For Each alink In Cells.Hyperlinks
strURL = alink.Address
If Left(strURL, 4) <> "http" Then
strURL = ThisWorkbook.BuiltinDocumentProperties("Hyperlink Base") & strURL
End If
Application.StatusBar = "Testing Link: " & strURL
Set objhttp = CreateObject("MSXML2.XMLHTTP")
objhttp.Open "HEAD", strURL, False
objhttp.Send
If objhttp.statustext <> "OK" Then
alink.Parent.Interior.Color = 255
End If
Next alink
Application.StatusBar = False
'Release objects to prevent memory issues
Set alink = Nothing
Set objhttp = Nothing
On Error GoTo 0
MsgBox ("Checking Complete!" & vbCrLf & vbCrLf & "Cells With Broken or Suspect Links are Highlighted in RED.")
End Sub
Old Answer Below
Combining your macro (which seems to be from here) with an alternative found on excelforum yields the below code. Give it a try and let me know if it works for you.
Sub TestHLinkValidity()
Dim rRng As Range
Dim fsoFSO As Object
Dim strPath As String
Dim cCell As Range
If MsgBox("Is the Active Sheet a Sheet with Hyperlinks You Would Like to Check?", vbOKCancel) = vbCancel Then
Exit Sub
End If
Set fsoFSO = CreateObject("Scripting.FileSystemObject")
Set rRng = ActiveSheet.UsedRange.Cells
For Each cCell In rRng.Cells
If cCell.Hyperlinks.Count > 0 Then
strPath = GetHlinkAddr(cCell)
If fsoFSO.FileExists(strPath) = False Then cCell.Interior.Color = 65535
End If
Next cCell
End Sub
Function GetHlinkAddr(rngHlinkCell As Range)
GetHlinkAddr = rngHlinkCell.Hyperlinks(1).Address
End Function
So I have a loop that exports data from a website. However, for each case, it starts a new session and closes. Is there a method to navigate and download for all the cases in just one IE11 session and then closing out? Below is the code that I have right now:
Public Sub Get_File()
Dim sFiletype As String 'Fund type reference
Dim sFilename As String 'File name (fund type + date of download), if "" then default
Dim sFolder As String 'Folder name (fund type), if "" then default
Dim bReplace As Boolean 'To replace the existing file or not
Dim sURL As String 'The URL to the location to extract information
Dim Cell, Rng As Range
Dim Sheet As Worksheet
'Initialize variables
Set Rng = Range("I2:I15")
Set Sheet = ActiveWorkbook.Sheets("Macro_Button")
For Each Cell In Rng
If Cell <> "" Then
sFiletype = Cell.Value
sFilename = sFiletype & "_" & Format(Date, "mmddyyyy")
sFolder = Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:J15"), 2, False)
bReplace = True
sURL = "www.preqin.com"
'Download using the desired approach, XMLHTTP / IE
If Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:W15"), 15, False) = 1 Then
Call Download_Use_IE(sURL, sFilename, sFolder, bReplace)
Else
Call Download_NoLogin_Use_IE(sURL, sFilename, sFolder, bReplace)
End If
Else
Exit Sub
End If
Next
End Sub
Private Sub Download_Use_IE(ByRef sURL As String, _
Optional ByRef sFilename As String = "", _
Optional ByRef sFolder As String = "", _
Optional ByRef bReplace As Boolean = True)
Dim oBrowser As InternetExplorer
Dim hDoc As HTMLDocument
Dim objInputs As Object
Dim ele As Object
On Error GoTo ErrorHandler
'Create IE object
Set oBrowser = New InternetExplorer
oBrowser.Visible = True
'Navigate to URL
Call oBrowser.navigate(sURL)
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
'Skips log in step if already signed into website
On Error GoTo LoggedIn
'Enter username
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_user_email").Value = "XXX"
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_user_password").Value = "XXX"
'Submit the sign in
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_btnLogin").Click
'Wait for website to load
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
LoggedIn:
'All PE
oBrowser.navigate Range("H3").Value
'Wait for website to load
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
'Set the htmldocument
Set hDoc = oBrowser.document
'Loop and click the download file button
Set objInputs = oBrowser.document.getElementsbyTagName("input")
For Each ele In objInputs
If ele.Title Like "Download Data to Excel" Then
ele.Click
End If
Next
'Wait for dialogue box to load
While oBrowser.Busy Or oBrowser.readyState > 3: DoEvents: Wend
Application.Wait (Now + TimeValue("0:00:02"))
'IE 9+ requires to confirm save
Call Download(oBrowser, sFilename, sFolder, bReplace)
'Close IE
oBrowser.Quit
Exit Sub
ErrorHandler:
'Resume
Debug.Print "Sub Download_Use_IE() " & Err & ": " & Error(Err)
End Sub
Modify your download_IE procedure to use a Browser that is passed to it:
Private Sub Download_Use_IE(oBrowser As InternetExplorer, _
ByRef sURL As String, _
Optional ByRef sFilename As String = "", _
Optional ByRef sFolder As String = "", _
Optional ByRef bReplace As Boolean = True)
Dim hDoc As HTMLDocument
Dim objInputs As Object
Dim ele As Object
On Error GoTo ErrorHandler
'Create IE object
oBrowser.Visible = True
'Navigate to URL
Call oBrowser.navigate(sURL)
......rest of code
Call Download(oBrowser, sFilename, sFolder, bReplace)
'Do not Close IE
Exit Sub
ErrorHandler:
'Resume
Debug.Print "Sub Download_Use_IE() " & Err & ": " & Error(Err)
End Sub
Then modify your procedure to pass this object:
Public Sub Get_File()
'declare all variables plus:
Dim oBrowser As InternetExplorer
Set oBrowser = New InternetExplorer
.....put additional code here.....
If Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:W15"), 15, False) = 1 Then
Call Download_Use_IE(oBrowser, sURL, sFilename, sFolder, bReplace)
Else
Call Download_NoLogin_Use_IE(oBrowser, sURL, sFilename, sFolder, bReplace)
End If
Else
Exit Sub
End If
Next
'Close IE
oBrowser.Quit
End Sub
You will need to do the same thing for the other procedure.
I am trying to enter the value of cell C4, which is gotten from an input box which assigns the value to the cell, into the search box after submitting at the first page but I am not able to as I keep getting an error 438. Is there something wrong with my codes after the input box?
And is there a way that I can have the codes wait until cell C4 is assigned with the value in the input box then continue with filling in the 2nd page?
Also, I am using Internet Explorer 11, what should my objItem.FullName Like be if I want to use the opened browser to work on?
Option Explicit
Const word1 As String = "C2"
Const word2 As String = "C3"
Const word3 As String = "C4"
Public Sub Test()
Dim objWindow As Object
Dim objIEApp As Object
Dim objShell As Object
Dim objItem As Object
Dim wordthree As String
On Error GoTo Fin
Set objShell = CreateObject("Shell.Application")
Set objWindow = objShell.Windows()
For Each objItem In objWindow
If LCase(objItem.FullName Like "*iexplore*") Then
Set objIEApp = objItem
End If
Next objItem
If objIEApp Is Nothing Then
Set objIEApp = CreateObject("InternetExplorer.Application")
objIEApp.Visible = True
End If
With objIEApp
.Visible = True
.Navigate "google.com"
While Not .ReadyState = 4
DoEvents
Wend
.Document.all.q.Value = Range(word1).Value
'.Document.all.q.Value = Range(word2).Value
.Document.forms(0).submit
End With
3word = InputBox("Enter 3rd word: ")
Range("C4").Value = wordthree
With objIEApp
.Visible = True
While Not .ReadyState = 4
DoEvents
Wend
.Document.all.q.Value = Range(word3).Value
.Document.forms(0).submit
End With
Fin:
If Err.Number <> 0 Then MsgBox "Error: " & _
Err.Number & " " & Err.Description
Set objWindow = Nothing
Set objShell = Nothing
End Sub
The first thing I can spot here is that you're attempting to name your variables starting with a number. In the VB world (VBA, VB.Net etc. all included), this is not valid & your code won't work.
Please see https://msdn.microsoft.com/en-us/library/office/gg264773.aspx for more info on variable naming rules.
Update:
The next thing & reason you're getting the error, is that you need to include a call to exit the method before the error handling routine code is called. Your code above now worked correctly for me with this "exit sub" statement added.
.Document.all.q.Value = Range(word3).Value
.Document.forms(0).submit
End With
**Exit Sub**
Fin:
If Err.Number <> 0 Then MsgBox "Error: " & _
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