I'm trying to convert pdfs into Excel spreadsheets. I have already added the "Microsoft Scripting Runtime" reference. Help?
Option Explicit
Sub PDF_To_Excel()
Dim setting_sh As Worksheet
Set setting_sh = ThisWorkbook.Sheets("Setting")
Dim pdf_path As String
Dim excel_path As String
pdf_path = setting_sh.Range("E11").Value
excel_path = setting_sh.Range("E12").Value
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
......
However I keep getting a
invalid procedure call or argument error
for Dim fso As New FileSystemObject
Help?
I always use the extended syntax:
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
It has never failed for me.
Related
I use this code to convert PDF Files to Excel.
Private Sub CommandButton2_Click()
Dim setting_sh As Worksheet
Set setting_sh = ThisWorkbook.Sheets("Tabelle1")
Dim pdf_path As String
Dim excel_path As String
pdf_path = setting_sh.Range("E11").Value
excel_path = setting_sh.Range("E12").Value
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Set fo = fso.GetFolder(pdf_path)
Dim wa As Object
Dim doc As Object
Dim wr As Object
Set wa = CreateObject("word.application")
'Dim wa As New Word.Application
wa.Visible = True
'Dim doc As Word.Document
Dim nwb As Workbook
Dim nsh As Worksheet
'Dim wr As Word.Range
For Each f In fo.Files
Set doc = wa.documents.Open(f.Path, False, Format:="PDF Files")
Set wr = doc.Paragraphs(1).Range
wr.WholeStory
Set nwb = Workbooks.Add
Set nsh = nwb.Sheets(1)
wr.Copy
nsh.Paste
nwb.SaveAs (excel_path & "\" & Replace(f.Name, ".pdf", ".xlsx"))
doc.Close False
nwb.Close False
Next
wa.Quit
MsgBox "Done"
End Sub
The problem is, other people also want to use this function, but they don't understand to how to add the Microsoft Scripting Runtime Reference in your VBA project. I tried to convert it to late binding, but it fails all the time. Can someone help me?
Thanks.
Change this:
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
to this:
Dim fso As Object
Dim fo As Object
Dim f As Object
Set fso = CreateObject("Scripting.FileSystemObject")
The next code will automatically add the necessary reference:
Sub addScrRunTimeRef()
'Add a reference to 'Microsoft Scripting Runtime':
'In case of error ('Programmatic access to Visual Basic Project not trusted'):
'Options->Trust Center->Trust Center Settings->Macro Settings->Developer Macro Settings->
' check "Trust access to the VBA project object model"
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Windows\SysWOW64\scrrun.dll"
End Sub
The above code may fail if Trust access to the VBA project object model check box is gray out, being disabled by restricted administrative security policies. In such a case, the following solution should be recommended:
To declare and set variables in Late binding way, declare and assign the objects in the next way:
Dim fso As Object, fo as Object, f as Object
set fso =CreateObject("Scripting.FileSystemObject")
It is also good to be known that Early binding is operationally faster than Late during run-time, and the programmer may benefit of intellisense suggestions, automatic capitalization of method names etc.
I'm trying to pass a string into the command line once I've opened it via shortcut. (I had to open it up this way due to permission issues and OneDrive being weird.)
I understand the code for the most part. The problem is how to pass a string into command prompt once it's opened since I'm not doing it the traditional way.
Is there a method to pass a string into this so command prompt can automate stuff I input?
Sub OpenFile()
Dim FileName As Variant
Dim FolderItem As Object
Dim FolderPath As Variant
Dim oFolder As Object
Dim oShell As Object
'Dim UserName As String
'UserName = InputBox("ex", "ex", "ex")
FolderPath = [B]"C:\Documents and Settings\users\Command Prmompt"[/B]
FileName = [B]"Command Prompt.lnk"[/B]
Set oShell = CreateObject("Shell.Application")
Set FolderItem = oShell.Namespace(FolderPath).ParseName(FileName)
FolderItem.Verbs.Item(0).DoIt
End Sub
Sub tryMethod()
Dim objTxt as textstream
Dim filename as string
fileName = "Z:\New folder\TextDoc.txt"
Set fSo = New Scripting.FileSystemObject
Set objTxt = fSo.OpenTextFile(fileName, ForReading)
str = objTxt.WriteBlankLines(1)
End Sub
No matter what number I put into the brackets after calling method writeblanklines I get the following error:
expected function or variable
I have checked documentation and do not see an example for this method. First two pages of google also didn't give me an example to work off of.
You have opened the file for reading Set objTxt = fSo.OpenTextFile(fileName, ForReading) and you are trying to write.
This is how to open it for writing:
Sub TestMe()
Dim objTxt As TextStream
Dim fso As Object
Dim filename As String
filename = "C:\Users\User\Desktop\nd.txt"
Set fso = New Scripting.FileSystemObject
Set objTxt = fso.OpenTextFile(filename, ForWriting)
objTxt.WriteBlankLines 23
End Sub
The MSDN documentation (from #braX comment) is not as good as one would expect - the ForWriting constant is present only in the example:
However, the ForWriting is present in the GitHub, maybe one day when the MSDN and the GitHub would be sync-ed it will be there as well:
I'm attempting to modify a VBA script from another post (26486871).
The script will download a Zip file, extract a text file and import the data to Excel.
I don't know VBA so I'll tackle each of the functions one at-a-time.
Create a temp directory with a randomized name................................Complete
Download a Zip file from a public server...............................................Complete
Extract the text file (20MB, tab-delimited)..............................................Error
Import the data into the open worksheet (overwrite the existing data)...Not Yet
On the Extract portion, I'm receiving a run-time error on the following line:
objOApp.Namespace(FileNameToUnzip).CopyHere objOApp.Namespace(varFileNameFolder).items, 256
"Run-time error '91: Object variable or With block variable not set."
When I hover my cursor over the variables while in Debug Mode, the directory and filenames are correct.
I'm unsure what is not set. I appreciate any help.
Option Explicit
'Main Procedure
Sub DownloadExtractAndImport()
Dim url As String
Dim targetFolder As String, targetFileZip As String, targetFileTXT As String
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
Dim newSheet As Worksheet
url = "http://www.example.com/data.zip"
targetFolder = Environ("TEMP") & "\" & RandomString(6) & "\"
MkDir targetFolder
targetFileZip = targetFolder & "data.zip"
targetFileTXT = targetFolder & "data.txt"
'1 download file
DownloadFile url, targetFileZip
'2 extract contents
Call UnZip(targetFileZip, targetFolder)
End Sub
Private Sub DownloadFile(myURL As String, target As String)
Dim WinHttpReq As Object
Dim oStream As Object
Set WinHttpReq = CreateObject("Msxml2.ServerXMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.send
myURL = WinHttpReq.responseBody
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile target, 1 ' 1 = no overwrite, 2 = overwrite
oStream.Close
End If
End Sub
Private Function RandomString(cb As Integer) As String
Randomize
Dim rgch As String
rgch = "abcdefghijklmnopqrstuvwxyz"
rgch = rgch & UCase(rgch) & "0123456789"
Dim i As Long
For i = 1 To cb
RandomString = RandomString & Mid$(rgch, Int(Rnd() * Len(rgch) + 1), 1)
Next
End Function
Private Function UnZip(PathToUnzipFileTo As Variant, FileNameToUnzip As Variant)
Dim objOApp As Object
Dim varFileNameFolder As Variant
varFileNameFolder = PathToUnzipFileTo
Set objOApp = CreateObject("Shell.Application")
objOApp.Namespace(FileNameToUnzip).CopyHere objOApp.Namespace(varFileNameFolder).items, 256
End Function
Dim mainFolder As String
Dim zipFolder As String
Dim destinationFolder As String
Dim oShell As Object
Dim oMainFolder As Object
Dim oDestinatioFolder As Object
Dim oZipFolder As Object
Dim oZipItems As Object
replace with
Dim mainFolder As Variant
Dim zipFolder As Variant
Dim destinationFolder As Variant
Dim oShell As Object
Dim oMainFolder As Object
Dim oDestinatioFolder As Object
Dim oZipFolder As Object
Dim oZipItems As Object
Comintem is right, you should edit your old question with the added code rather than post a near identical new question. Perhaps keep this question and delete the old one.
To answer your question, it looks as if you're passing your arguments in the wrong order to your UnZip function. Try changing the line to:
Call UnZip(targetFolder, targetFileZip)
Update
It's difficult to diagnose the issues as your objects are being created and its properties/methods being called all on one line. Judging by the nature of your questions it doesn't seem as though your VBA knowledge is particularly vast and that you're trying to construct a working solution by tying various pieces of web code together. It's not my position to judge that kind of approach but my advice would be, if you take this approach, to create your objects one at a time and call its methods one at a time. This will make it far easier to diagnose your code.
I've tried to rewrite elements of your code to show you how this could be done. It might be a bit overkill but at least it'll help you identify the precise location of any problems. Obviously change the folder names to your own.
Dim mainFolder As String
Dim zipFolder As String
Dim destinationFolder As String
Dim oShell As Object
Dim oMainFolder As Object
Dim oDestinatioFolder As Object
Dim oZipFolder As Object
Dim oZipItems As Object
'Define the folder names
mainFolder = "C:\Users\User\Downloads\SO\" 'change to your own folder name
zipFolder = "sqlite-shell-win32-x86-3071700.zip" 'an old sqlite download = change to your name
destinationFolder = Left(zipFolder, Len(zipFolder) - 4) 'name of zip folder minus the '.zip'
'Create the new destination folder
MkDir mainFolder & destinationFolder
'Acquire the folder items
'create the shell object
Set oShell = CreateObject("Shell.Application")
'create the main folder object as Folder3 item
Set oMainFolder = oShell.Namespace(CVar(mainFolder)) 'argument must be a variant
'create the destination folder object as Folder3 item
Set oDestinatioFolder = oMainFolder.Items.Item(CVar(destinationFolder & "\")).GetFolder
'create the zip folder object as Folder3
Set oZipFolder = oMainFolder.Items.Item(CVar(zipFolder)).GetFolder
'Extract the zip folder items and write to desination folder
oDestinatioFolder.CopyHere oZipFolder.Items, 256
Does any one know why the
.writeblanklines 3
does not work? I've tried plenty of different ways and it always seems to just overwrite the line in the textfile.
Private Sub CommandButton3_Click()
Dim fso As FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
Dim fsofolder As Folder
Set fsofolder = fso.GetFolder("U:\files")
Dim file1 As file
Dim a As Integer
Dim b As String
b = "U:\files\" & ListBox1.Value
fso.OpenTextFile(b, ForWriting).WriteBlankLines 3
fso.OpenTextFile(b, ForWriting).WriteLine (TextBox3.Value)
See: http://msdn.microsoft.com/en-us/library/aa265347(v=vs.60).aspx
If you want to append content, then use ForAppending when opening the file.