I'm having a problem with this piece of my code in VBA and I can't figure out why it isn't working! I've tried another code to see if it was the loop that has the issue but the issue is specifically opening the files and not iterating through them.
Sub fileloop(Path)
Dim strFile As String, strPath As String
Dim MyBook As Workbook
strPath = Path '& "\*.csv"
strFile = Dir(strPath & "\*.csv")
MsgBox (strFile)
While strFile <> ""
'placed another messagebox here to see if the strFile was the same inside the loop.
MsgBox (strFile)
'this line has the error.
Workbooks.OpenText FileName:=strFile, _
DataType:=xlDelimited, Comma:=True, Local:=True
set MyBook = ActiveWorkbook
Call SortColumnB(MyBook)
strFile = Dir
Wend
End Sub
The error message I get goes something like this:
'AC000W0009.csv' could not be found. Check the spelling of the file name, and verify that the file location is correct.
If you are trying to open the file from your list of most recently used files, make sure that the file has not been renamed, moved, or deleted.
I've tried so many variations apart from the one listed above and I can't understand why VBA won't recognize that the file exists.
EDIT
Going off of what Mike said about opening a file with the complete path the changes I made to the code to let it open .csv files:
strPath = Path & "\"
strFile = Dir(strPath & "*.csv")
While strFile <> ""
MsgBox (strFile) 'added path to file name.
Workbooks.OpenText FileName:=strPath & strFile, _
DataType:=xlDelimited, Comma:=True, Local:=True
I beleve the Dir only returns only the filename.
If you want to open it, you need to add the path to the file name returned by Dir.
There's some good examples here
Related
I am trying to open file from the same folder as the main workbook. The problem is that the name is not permanent and just one word stays always inside the name - "NAME".
I want to use specific method with Thisworkbook.Path to open the xlsx file but it is not finding the workbook with the code.
that is the relavant part of code:
Sub RemoveDuplicats()
Dim Harel As Workbook
Dim SAP As Workbook
Dim Path As String
Dim Found As String
Path = ThisWorkbook.Path
Found = Dir(Path & "*NAME*.xlsx") 'open SAP report
If Found <> "" Then
Set SAP = Workbooks.Open(Path & Found)
End If
End Sub
ThisWorkbook.Path Returns the path without trailing backslash,
try
Found = Dir ( Path & "\" & "*NAME*.xlsx")
You would need to Loop though all Fiels in this Folder and compare the File Names like this:
Dim StrFile As String
StrFile = Dir(ThisWorkbook.Path & "\*" & ".xlsm")
Do While Len(StrFile) > 0
If StrFile Like "*Name*" Then
MsgBox StrFile 'This will be your File
End If
StrFile = Dir
Loop
Simple code to loop paste .emf files into word:
Sub LoopEMF()
Dim sPic As String
Dim sPath As String
sPath = "C:\Users\me\Desktop\Test2\"
sPic = Dir(sPath & "*.emf")
Do While sPic <> ""
Selection.TypeParagraph
Selection.InlineShapes.AddPicture _
FileName:=sPath & sPic, _
LinkToFile:=False, SaveWithDocument:=True
sPic = Dir
Selection.TypeParagraph
Loop
End Sub
Rather than a specified directory, I simply want to look in the active directory in which the word file (that is open) is located. Much searching has yielded no clue - which is surprising, embarrassing and probably means I'm not using the right key words.
Help?
When I open an Excel document D:\db\tmp\test1.xlsm:
CurDir() returns C:\Users\[username]\Documents
ActiveWorkbook.Path returns D:\db\tmp
So CurDir() has a system default and can be changed.
ActiveWorkbook.Path does not change for the same saved Workbook.
For example, CurDir() changes when you do "File/Save As" command, and select a random directory in the File/Directory selection dialog. Then click on Cancel to skip saving. But CurDir() has already changed to the last selected directory.
From:
How to get current working directory using vba?
Even more embarrassing - I had been using the correct code:
Sub NewLoopEMF()
Dim sPic As String
Dim sPath As String
sPath = ActiveDocument.path & "\"
sPic = Dir(sPath & "*.emf")
Do While sPic <> ""
Selection.TypeParagraph
Selection.InlineShapes.AddPicture _
FileName:=sPath & sPic, _
LinkToFile:=False, SaveWithDocument:=True
sPic = Dir
Selection.TypeParagraph
Loop
End Sub
Unfortunately, the active directory is in a synced SharePoint folder, so the returned name is in hypertext (http://all the rest/) and with this, all you know what breaks loose. I figured this out by using this code:
Sub GetActiveDocumentPath()
MsgBox ActiveDocument.path
End Sub
So it seems the simple solution is to not use a sharepoint folder to store the items. Anyone have a clever solution for those of us working in the SharePoint environment?
I am trying to set up a macro to pull all excel files in a folder into a database in access. I have the below code, but when I run the macro, it errors out into "No Files Found," so intFile = 0. However, there are files in the chosen folder. Why is it not finding them? I think I messed up the linking piece too but one problem at a time. I am obviously pretty new to VBA, so any help would be appreciated!
Thanks,
Option Compare Database
Option Explicit
'code will link to excel and pull site survey files into access tables
'Setting the path for the directory
Const strPath As String = "S:\LOG\PURCHASI\Daniel Binkoski\Outlook Attachments\R7398Z Look Forward Daily Snapshot"
'FileName
Dim strFile As String
'Array
Dim strFileList() As String
'File Number
Dim intFile As Integer
Sub Sample()
strFile = Dir(strPath & "*.xlsx")
'Looping through the folder and building the file list
strFile = Dir(strPath & "*.xlsx")
While strFile <> ""
'adding files to the list
intFile = intFile + 1
ReDim Preserve strFileList(1 To intFile)
strFileList(intFile) = strFile
strFile = Dir()
Wend
'checking to see if files where found
If intFile = 0 Then
MsgBox "No Files Found"
Exit Sub
End If
'going through the files and linking them to access
For intFile = 1 To UBound(strFileList)
DoCmd.TransferSpreadsheet acLink, , _
strFileList(intFile), strPath & strFileList(intFile), True, "A1:M50"
Next
MsgBox UBound(strFileList) & "Files were linked"
End Sub
try:
strFile = Dir(strPath & "\*.xlsx", vbNormal)
or add a final "\" onto your strPath value
You need another path separator to show you're looking in a directory, not at one.
I often use something like:
Dir(strPath & IIf(Right(strPath, 1) = "\", vbNullString, "\"))
as a check to ensure that the path always ends in a trailing backslash.
I need your help regarding an add-in I created using VBA, then I saved as add-in to be able to use on all Excel workbooks and also send it to my friends.
The add-in simply saves the printed area in the active sheet as a PDF file with the same name of the workbook, it saves the PDF to the desktop and works fine as a macro.
But when I save as PDF and use it, it saves the PDF file with the same name of the add-in, not as the workbook`s name.
Any suggestions?
The VBA code is:
Sub Save_as_pdf()
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = "C:\Users\" & Environ("UserName") & "\Desktop\" & ThisWorkbook.Name
If FSO.FileExists(ThisWorkbook.FullName) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=sNewFilePath, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
End Sub
To elaborate on Matteo NNZ's comment above:
ThisWorkbook refers to the workbook in which the code is currently being executed from (in this case, the add-in)
ActiveWorkbook refers to the workbook that is currently active within the same instance of Excel.
I want to open 4 different Excel files saved under same folder using VBA code, but the folder path is not fixed.
Let's say, I have 4 Excel files named A.xlsx, B.xlsx, C.xlsx & D.xlsx under folder named 22-Feb-15 (This folder name will change everyday, but the file names will remain same).
I want VBA code so that I can select the folder manually and once it is selected, all 4 files will open one by one (there are other files too, but I need to open only these 4 files).
Please see below:
Sub FolderSelect()
Dim intResult As Integer
Dim fldrPath As String
intResult = Application.FileDialog(msoFileDialogFolderPicker).Show
If intResult <> 0 Then
fldrPath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)
Workbooks.Open Filename:=fldrPath & "\" & "A.xlsx"
Workbooks.Open Filename:=fldrPath & "\" & "B.xlsx"
Workbooks.Open Filename:=fldrPath & "\" & "C.xlsx"
Workbooks.Open Filename:=fldrPath & "\" & "D.xlsx"
End If
End Sub
You can change file names and/or add new files by following the same structure