Read Data From excel with vb.net - vb.net

I have a vb.net console application and i am trying to read data from all excel files in a folder. In the second loop i get these error.
An unhandled exception of type 'System.ArgumentException' occurred in Microsoft.VisualBasic.dll
Additional information: Argument 'Prompt' cannot be converted to type 'String'.
Thanks for help.
Here is my code...
Sub Main()
Dim objFSO, objStartFolder, objFolder, colFiles, Path, a
objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Users\Administrator\Desktop\Excel Files"
objFolder = objFSO.GetFolder(objStartFolder)
colFiles = objFolder.Files
For Each objFile In colFiles
Path = objStartFolder + "\" + objFile.Name
Dim objexcel, objWorkbook, ex
objexcel = CreateObject("Excel.Application")
objexcel.Application.Visible = True
objWorkbook = objexcel.Workbooks.Open(Path)
ex = objWorkbook.Worksheets(1)
For i As Integer = 1 To 50
a = ex.Cells(i, 5)
MsgBox(a)
Next
objexcel.Quit()
Next
End Sub

ex.Cells(i, 5) doesn't return a string, rather an object representing the Range you've specified. So to access the value you need to change the type
MessageBox.Show(CType(ex.Cells(i, 5), Microsoft.Office.Interop.Excel.Range).Value.ToString())
You will need to add a reference to Microsoft.Office.Interop.Excel in your project. You will then also be able to strongly type your Excel objects if you want, ie:
Dim objExcel As New Microsoft.Office.Interop.Excel.Application()
Also on a side note you should probably stop using COM objects (Scripting.FileSystemObject) and use native managed .Net code instead. You can get the same functionality as above by just using the following code
'Get me all filenames with file extension .xlsx
Dim fileNames() As String = System.IO.Directory.GetFiles("C:\Users\Administrator\Desktop\Excel Files\")
'Loop through array of filenames
For Each fileName As String In fileNames
'Other excel code here
objExcel.Workbooks.Open(fileName)
Next

Related

Open other application from vba

I am working on a macro to open a file(might already be open) and save with new name and then open the new file from vba in excel.
This file can Powerpoint,mathcad,visio, word etc..(can also be template files such as dotx etc..)
So my idea is that:
I first need to figure out if the application is open or not,
then I somehow need to figure if the file is open or not,
then save it with the new filename.
Open the new document
Go through the document and dumps custom variables into the database, populate custom variables from database(Not shown in code below, seperate module)
Activate the new document so that the user can edit it.
Public Sub saveAsVBADocument(filenameNew As String, fileNameOld As String, applicationType As String)
Dim objectApplication As Object
Dim documentApplication As Object
On Error Resume Next
Set objectApplication = GetObject(, applicationType)
On Error GoTo 0
If objectApplication Is Nothing Then
Set objectApplication = CreateObject(applicationType)
End If
objectApplication.Visible = True
On Error Resume Next
Set documentApplication = objectApplication.Workbooks(FileHandling.GetFilenameFromPath(fileNameOld)) 'Excel
Set documentApplication = objectApplication.Documents(FileHandling.GetFilenameFromPath(fileNameOld)) 'Word
Set documentApplication = objectApplication.WorkSheets(FileHandling.GetFilenameFromPath(fileNameOld)) 'Mathcad
Set documentApplication = objectApplication.Presentations(FileHandling.GetFilenameFromPath(fileNameOld)) 'PowerPoint
Set documentApplication = objectApplication.Projects(FileHandling.GetFilenameFromPath(fileNameOld)) 'MS Project "Msproject.Application"
Set documentApplication = objectApplication.Documents(FileHandling.GetFilenameFromPath(fileNameOld)) 'MS Visio "Visio.Application"
If documentApplication Is Nothing Then
Set documentApplication = objectApplication.FileOpen(fileNameOld) ' add read only
End If
documentApplication.SaveAs filename:=filenameNew
Set objectApplication = Nothing
Set documentApplication = Nothing
End Sub
What is a possible solution to handle all vba acceptable document types?
You can use GetObject("Filename") to open a file directly in its application. So something like this can open any file that has its extension in the Windows Registry. That will be most file types; certainly the Office applications. Whether you'll be able to use SaveAs will depend on whether those applications support OLE Server (meaning they have a coding interface exposed). Again, all the Office applications do support this.
You'll probably want to put in some error-handling for the case the application for the file extension can't be found in the Registry. And of course in case the file name doesn't exist.
My example is for Excel and Word, only - you should be able to fill in others. My code makes sure the file is visible and available to the user as that makes it easier to trouble-shoot. You can, of course, change that once you have everything working satisfactorily.
Sub OpenFileInUnknownApp()
Dim objFile As Object
Dim objApp As Object
Dim sPath As String, sExt As String
Dim sFileName As String
Dim sAppName As String
Dim snewfilename As String
sPath = "C:\Test\"
sFileName = sPath & "Quote.docx" 'RngNames.xlsx"
snewfilename = sPath & "NewName"
'''Open the file in its application
Set objFile = GetObject(sFileName)
Set objApp = objFile.Application
sAppName = objApp.Name
Select Case sAppName
Case Is = "Microsoft Excel"
Dim wb As Excel.Workbook
sExt = "xlsx"
objApp.Visible = True
Set wb = objFile
wb.Activate
wb.Windows(1).Visible = True
objApp.UserControl = True 'so that it "lives" after the code ends
objApp.Activate
wb.SaveAs "sNewFileName" & sExt
Case Is = "Microsoft Word"
Dim doc As word.Document
sExt = "docx"
objApp.Visible = True
Set doc = objFile
objApp.Activate
doc.SaveAs2 "sNewFileName" & sExt
Case Else
End Select
Set objFile = Nothing
Set objApp = Nothing
End Sub

Error reading each file from dir in vb

I am getting this error while i am trying to read one by one all files in a dir, and also reading the text inside
An unhandled exception of type 'System.NullReferenceException' occurred in WindowsApplication1.exe
Additional information: Object reference not set to an instance of an object.
It is going good only for the first file , but when it starts another loop and gets the secound file from that folder there comes the problem.
This is my code
Dim theString As String
Dim path As String
Dim StrFile, str_5 As String
Dim fso As New FileSystemObject
Dim file As TextStream
Dim line As String
'theString = ""
path = "C:\IN\"
StrFile = Dir(path & "*.txt")
Do While StrFile <> ""
file = fso.OpenTextFile(path & StrFile)
Do While Not file.AtEndOfLine
line = file.ReadLine
If InStr(1, line, line.Substring(142, 1), vbTextCompare) = 5 Then
'Debug.Print(StrFile)
str_5 = str_5 & line
End If
Loop
file.Close()
file = Nothing
fso = Nothing
StrFile = Dir()
Loop
Just for other people with the same problem, the answer is to just remove this line
fso = Nothing

save pptx as pdf through excel

I am trying to convert all pptx files in a give path to pdf files.
my code:
Sub pptxtopdf()
Dim ppt As Object
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
On Error Resume Next
Set ppt = GetObject(, "PowerPoint.Application")
If ppt Is Nothing Then
Set ppt = CreateObject("PowerPoint.Application")
End If
On Error GoTo 0
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("P:\Operations\Data & Deliverables\Projects\Amica\presentation_workspace\1_ spring 2015\Presentations\Volvo")
i = 1
'loops through each file in the directory
For Each objFile In objFolder.Files
Set WDReport = ppt.Presentations.Open(objFile.Path)
Dim FileName2 As String
FileName2 = Replace(objFile.Path, "pptx", "pdf")
'WDReport.ExportAsFixedFormat FileName2, ppFixedFormatTypePDF
WDReport.SaveAs FileName2, ppSaveAsPDF
WDReport.Close
ppt.Quit
Set ppt = Nothing
Set WDReport = Nothing
i = i + 1
Next objFile
End Sub
error msg
Presentation.SaveAs : Invalid enumeration value.
Cannot see what I'm doing wrong?
same problem as here but the solution didnt work for me - Excel macro to save pptx as pdf; error with code
You are late binding PowerPoint.Application so its enumeration values are not exposed or available in the global VBA namespace.
As you have not added option explicit to warn you of undeclared variables your use of the undeclared ppSaveAsPDF causes no error but has no value.
Add:
const ppSaveAsPDF as long = 32
To the top of the module to provide the expected value to SaveAs.

Copy Worksheet Object Defined Error in Excel

I see this issue has come up a handful of times on this forum however none of the solutions have helped me. The code below actually did work, but then it started throwing an application-defined or objected defined error and now will not work. The code runs from within an Excel template, opens up each Excel report in the directory, then pastes 2 worksheets into the document.
Sub updateED()
Dim pathout, pathin As String
Dim WbOutput As Workbook
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(filepath)
'step through each xls file
For Each objFile In objFolder.Files
If InStr(objFile, ".xls") Then
Set WbOutput = Workbooks.Open(objFile)
Application.DisplayAlerts = False
'drop in additional templates
ThisWorkbook.Sheets(Array("Business Entity", "Facility")).Copy before:=WbOutput.Sheets("Mbr_Detail_ED")
End If
Next
End Sub
See if this helps
Option Explicit
Sub updateED()
Dim Pathout As String
Dim Pathin As String
Dim WbOutput As Workbook
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\Temp\")
'step through each xls file
For Each objFile In objFolder.Files
If InStr(objFile, ".xls") Then
Set WbOutput = Workbooks.Open(objFile)
Application.DisplayAlerts = False
'drop in additional templates
ThisWorkbook.Sheets(Array("Business Entity", "Facility")).Copy before:=WbOutput.Sheets("Mbr_Detail_ED")
End If
Next
End Sub

List files of certain pattern using Excel VBA

How to list all the files which match a certain pattern inside a user specified directory? This should work recursively inside the sub folders of the selected directory. I also need a convenient way(like tree control) of listing them.
It appears that a couple answers talk about recursion, and one about regex. Here's some code that puts the two topics together. I grabbed the code from http://vba-tutorial.com
Sub FindPatternMatchedFiles()
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objRegExp As Object
Set objRegExp = CreateObject("VBScript.RegExp")
objRegExp.pattern = ".*xlsx"
objRegExp.IgnoreCase = True
Dim colFiles As Collection
Set colFiles = New Collection
RecursiveFileSearch "C:\Path\To\Your\Directory", objRegExp, colFiles, objFSO
For Each f In colFiles
Debug.Print (f)
'Insert code here to do something with the matched files
Next
'Garbage Collection
Set objFSO = Nothing
Set objRegExp = Nothing
End Sub
Sub RecursiveFileSearch(ByVal targetFolder As String, ByRef objRegExp As Object, _
ByRef matchedFiles As Collection, ByRef objFSO As Object)
Dim objFolder As Object
Dim objFile As Object
Dim objSubFolders As Object
'Get the folder object associated with the target directory
Set objFolder = objFSO.GetFolder(targetFolder)
'Loop through the files current folder
For Each objFile In objFolder.files
If objRegExp.test(objFile) Then
matchedFiles.Add (objFile)
End If
Next
'Loop through the each of the sub folders recursively
Set objSubFolders = objFolder.Subfolders
For Each objSubfolder In objSubFolders
RecursiveFileSearch objSubfolder, objRegExp, matchedFiles, objFSO
Next
'Garbage Collection
Set objFolder = Nothing
Set objFile = Nothing
Set objSubFolders = Nothing
End Sub
As a general pointer, take a look at Application.FileSearch, recursive functions, Userforms and the 'Microsoft TreeView Control'.
FileSearch can be used to find files within a folder matching a pattern, a recursive function can call itself until all paths have been exhausted, a UserForm can host controls for displaying your data and the TreeView control can display your file system.
Bear in mind that there are pre-built functions/controls which can be used for displaying file systems, e.g. Application.GetOpenFileName, Application.GetSaveAsFileName, Microsoft WebBrowser (given a 'file://...' URL).
Try Windows Scripting - File System Objects. This COM object which can be created form vba has functions for listing directories etc.
You can find documentation on MSDN
Not exactly what you asked for, but I thought I would post this here as it is related.
This is modified from the code found at http://www.cpearson.com/excel/FOLDERTREEVIEW.ASPX
This requires the reference Microsoft Scripting Runtime.
Sub ListFilePaths()
Dim Path As String
Dim Files As Long
Path = "C:\Folder"
Files = GetFilePaths(Path, "A", 1)
MsgBox "Found " & Files - 1 & " Files"
End Sub
Function GetFilePaths(Path As String, Column As String, StartRow As Long) As Long
Dim Folder As Scripting.Folder
Dim SubFolder As Scripting.Folder
Dim File As Scripting.File
Dim FSO As Scripting.FileSystemObject
Dim CurrentRow As Long
Set FSO = New Scripting.FileSystemObject
Set Folder = FSO.GetFolder(folderpath:=Path)
CurrentRow = StartRow
For Each File In Folder.Files
Range(Column & CurrentRow).Value = File.Path
CurrentRow = CurrentRow + 1
Next File
For Each SubFolder In Folder.SubFolders
CurrentRow = GetFilePaths(SubFolder.Path, Column, CurrentRow)
Next SubFolder
GetFilePaths = CurrentRow
Set Folder = Nothing
Set FSO = Nothing
End Function
I see that the people above me have already answered how to recurse through the file tree, This might interest you in searching for patterns in the file/file name. It is a Function for VBA that will allow regular expressions to be used.
Private Function RegularExpression(SearchString As String, Pattern As String) As String
Dim RE As Object, REMatches As Object
'Create the regex object'
Set RE = CreateObject("vbscript.regexp")
With RE
.MultiLine = False
.Global = False
.IgnoreCase = True
'set the search pattern using parameter Pattern'
.Pattern = Pattern
End With
'Search for the pattern'
Set REMatches = RE.Execute(SearchString)
If REMatches.Count > 0 Then
'return the first match'
RegularExpression = REMatches(0)
Else
'nothing found, return empty string'
RegularExpression = ""
End If
End Function
You can use this to search the file names for patterns. I suggest regular expressions home for more information on how to use Regular expressions