在记事本中使用不带SendKeys的VBA从PDF保存文本文件

在记事本中使用不带SendKeys的VBA从PDF保存文本文件,vba,pdf,text,Vba,Pdf,Text,所以,我要做的是获取一个pdf文件,用internet explorer打开它,从中复制文本,将文本粘贴到记事本中的文本文件中,并将该文件与创建它的pdf文件同名保存。到目前为止,我已经完成了所有这一切,除了在获得所需数据后保存文本文件。我发现自己现在陷入困境,任何想法都会有帮助 以下是我目前掌握的代码: Set b2 = ThisWorkbook Set ie = CreateObject("InternetExplorer.Application") strPath = "C:\Users

所以,我要做的是获取一个pdf文件,用internet explorer打开它,从中复制文本,将文本粘贴到记事本中的文本文件中,并将该文件与创建它的pdf文件同名保存。到目前为止,我已经完成了所有这一切,除了在获得所需数据后保存文本文件。我发现自己现在陷入困境,任何想法都会有帮助

以下是我目前掌握的代码:

Set b2 = ThisWorkbook

Set ie = CreateObject("InternetExplorer.Application")
strPath = "C:\Users\353281\Desktop\test 134.pdf"

ie.Visible = True
ie.navigate (strPath)

Do While ie.Busy And ie.ReadyState <> 4
        DoEvents
    Loop


Application.Wait Now + TimeSerial(0, 0, 2)
    AppActivate strPath
    SendKeys "^(a)", True
    Application.Wait Now + TimeSerial(0, 0, 1)

    Do
        On Error Resume Next
        SendKeys "^(c)", True
    Loop While Err.Number <> 0
np = Shell("Notepad.exe", vbNormalFocus)


AppActivate np
SendKeys "^(v)", True
'tried the SendKeys method of saving my text file here, not to much avail
SendKeys "^(s)", True

'this bit here finds the file name of strPath
a = InStrRev(strPath, "\")
b = InStrRev(strPath, ".")
c = Mid(strPath, a + 1, b - a - 1)

'haven't got anything after this point but a few failed attempts

很抱歉,代码太乱了,我不会把重点放在结构上,直到我有了一个可以工作的东西

我会这样做:

Dim NP as object

set NP = CreateObject("Notepad.Application")

'copy the text from the .PDF as you do now

NP.paste
NP.SaveAs Filename:=<your file name>

注意:这是完全未经测试的,但应作为一个框架。我没有查看记事本对象模型来确认我的方法名称是否正确。

因此,最终对我有效的是如下代码:

Dim b2 As Workbook
Dim ie As Object
Dim np As Object

Sub test4()
Set b2 = ThisWorkbook

Set ie = CreateObject("InternetExplorer.Application")
strPath = "C:\Users\353281\Desktop\test 134.pdf"

ie.Visible = False
ie.navigate (strPath)

Do While ie.Busy And ie.ReadyState <> 4
    DoEvents
Loop

Application.Wait Now + TimeSerial(0, 0, 2)
AppActivate strPath
SendKeys "^(a)", True
Application.Wait Now + TimeSerial(0, 0, 1)

Do
    On Error Resume Next
    SendKeys "^(c)", True
Loop While Err.Number <> 0

ie.Quit

Set np = CreateObject("Word.Application")
AppActivate np
np.documents.Add
np.Visible = False
np.Selection.pasteandformat wdpastedefault

b = InStrRev(strPath, ".")
filenm = Mid(strPath, 1, b - 1)

np.activedocument.SaveAs2 Filename:=filenm, FileFormat:=2
np.activedocument.Close
np.Quit

np = Nothing
ie = Nothing
SendKeys "{NUMLock}", True

End Sub

我发现使用Word比使用记事本创建文本文档成功得多。此代码将获取pdf,在IE中打开它,选择所有文本,复制到剪贴板,然后将其粘贴到word文档中,然后将其保存为文本文件,保存在与原始pdf相同的文件夹中。

您能否以创建IE对象相同的方式创建记事本对象?记事本是否公开对象模型??如果是这样,那么粘贴和保存应该非常简单。