below is a file path i need the workbook to open however this file path changes so i have an input box that gives the file path and dimmed as location
Workbooks.Open ("C:\Users\AylingB\OneDrive - TGE\Desktop\coding test for calcs\C5663-TD37-CAL-1900-0005_A TANK DOME ROOF STRUCTURE.xlsm")
so i instead have this
A = Range("p1")
B = Range("p2")
C = Range("p3")
Dim location As String
location = "(" & """" & A & B & C & """" & ")"
Debug.Print location
Workbooks.Open location
p1-3 is the file path split in certain cells(this cannot change unfortunately)
this does not work however even tho it equals the exact same pathway (brackets and quotaton marks included)
is there any way of doing this without having to go to the vba code every time and changing it
i have tried concatenation to bring everything together.
ive also tried it with and without brackets
with and without speech marks
im just abit lost as when i do debug .print the code looks exactly the same but only works when its typed out fully
The GetFileName function will ask open the FileDialog and ask you to select the file - starting in the same folder as the file containing the code (ThisWorkbook).
Test shows how to use it - and store a reference to it in a variable.
GetFileName is the function you should copy to your project.
Sub Test()
Dim MyFilePath As String
MyFilePath = GetFileName 'Ask for the filename & path
Dim MyFile As Workbook
'Check that a file was selected, and it wasn't this file.
If MyFilePath <> "" And MyFilePath <> ThisWorkbook.FullName Then
Set MyFile = Workbooks.Open(MyFilePath) 'Open the file and set a reference to it.
'Rest of your code.
'Use "MyFile" whenever referencing the workbook.
Dim MySheet As Worksheet
Set MySheet = MyFile.Worksheets(1)
Dim LastRow As Long
LastRow = MySheet.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox MyFile.Name & " contains " & MyFile.Worksheets.Count & " worksheets." & vbCr & _
"The last row in " & MySheet.Name & " column A is " & LastRow
End If
End Sub
Private Function GetFileName() As String
Dim FD As FileDialog
Set FD = Application.FileDialog(msoFileDialogFilePicker)
With FD
.InitialFileName = ThisWorkbook.Path & Application.PathSeparator
.AllowMultiSelect = False
'Not needed unless want to limit to specific file types.
.Filters.Clear 'On it's own will set filter to "All Files", "*.*"
.Filters.Add "Excel Files", "*.xlsx, *.xlsm, *.xls"
.Filters.Add "Other Files", "*.csv, *.someotherextension"
.FilterIndex = 2 'Display "Other Files" as default.
If .Show = -1 Then
GetFileName = .SelectedItems(1)
End If
End With
Set FD = Nothing
End Function
Related
The goal is to combine two functions or make them compatible with each other. There is errors when it comes to the part when the path of the chosen file is not refer to in the same manner as the path of the found file within the loop if available in the folder.
I get an error. See "HERE IS WHERE I GET THE ERROR" at
Dim closedBook As Workbook: Set closedBook = Workbooks.Open(sFilePath)
'main code that run is doing something like search for file within folder,
'loop and get the latest file and generates a path and name for next
'function which is to copy a sheet from the found file over to the main
'workbook and so.
'What I'm trying to to is to build a failsafe, lets say file is not pushed
'or placed whin this predestinated folder, then instead of doing nothing,
'dialog box opens up and files gets chosen instead.
Option Explicit
Sub ImportAndFormatData()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Const sFolderPath As String = "C:\Temp\"
'Search for newest file
Dim sFileName As String: sFileName = Dir(sFolderPath & "_pr11*.xlsx")
If Len(sFileName) = 0 Then Call OpenDialogBox
Dim cuDate As Date, sFileDate As Date, cuPath As String, sFilePath As String
Do Until Len(sFileName) = 0
cuPath = sFolderPath & sFileName
cuDate = FileDateTime(cuPath)
'Debug.Print "Current: " & cuDate & " " & cuPath ' print current
If cuDate > sFileDate Then
sFileDate = cuDate
sFilePath = cuPath
End If
sFileName = Dir
Loop
'Debug.Print "Result: " & sFileDate & " " & sFilePath ' print result
'Open newest file - HERE IS WHERE I GET THE ERROR
Dim closedBook As Workbook: Set closedBook = Workbooks.Open(sFilePath)
closedBook.Sheets("Analyse").Copy After:=ThisWorkbook.Sheets("PR11_P3")
closedBook.Close SaveChanges:=False
'code dose not end here but that part don't need to be included here since
'its just formatting
End Sub
In OpenDialogBox, I'm tying to enforce a specific title (only this file/report is correct source for the entire code or rather rest of the code).
See "GIVES ERROR DOSENT WORK" at
.Filters.Add "Excel filer", "_pr11*.xlsx?", 1
Sub OpenDialogBox()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Filters.Clear
.Title = "Välj valfri PR11"
.Filters.Add "Excel filer", "_pr11*.xlsx?", 1 'GIVES ERROR DOSENT WORK
.AllowMultiSelect = False
If .Show = True Then
Debug.Print .SelectedItems(1)
Debug.Print Dir(.SelectedItems(1))
End If
End With
End Sub
This combines both the Dir() and FileDialog approaches:
Sub ImportAndFormatData()
Dim fSelected As String, wb As Workbook
fSelected = InputFile()
If Len(fSelected) > 0 Then
Set wb = Workbooks.Open(fSelected)
wb.Sheets("Analyse").Copy After:=ThisWorkbook.Sheets("PR11_P3")
wb.Close False
End If
End Sub
Function InputFile() As String
Const SRC_FOLDER As String = "C:\Temp\"
Dim f, fSelected As String, latestDate As Date, fdt
f = Dir(SRC_FOLDER & "*_pr11*.xlsx") 'first check the configured folder for a match
If Len(f) > 0 Then
'found matching file at specified path: loop for the newest file
Do While Len(f) > 0
fdt = FileDateTime(SRC_FOLDER & f)
If fdt > latestDate Then
fSelected = SRC_FOLDER & f
latestDate = fdt
End If
f = Dir()
Loop
InputFile = fSelected
Else
'no match at specified path - allow user selection
With Application.FileDialog(msoFileDialogFilePicker)
.Filters.Clear
.Title = "Välj valfri PR11"
.Filters.Add "Excel filer", "*.xlsx" 'filter only allows extension: no filename wildcards...
.AllowMultiSelect = False
If .Show Then InputFile = .SelectedItems(1)
End With
End If
End Function
We import a CSV file into excel from Creo, this is our Bill of materials, We create the drawing PDF's and DXF's and save them in two 'MASTER' folders. When issuing the drawings to a manufacturer we must copy every individual drawing to a separate folder before sending.
The solution I am working on is to use a userform to select the 'copyfrom' location and 'copyto' location, on the 'run' command button, a sub should copy the files across.
I have the used the copy code by entering the folder locations in the Sub routine, but i need to allow other users to choose other files. The userform is adding the folder locations to the specific textboxes, but the next sub routine to copy the pdfs will not work.
I think it may be the textbox value is not recorded?
As a side I would also like to return the number of moved PDF's as part of the message in the Message box once the routine has completed. This may be different to the number of used cells in column B
The part number of the drawing will always be in column B
I haven't created the DXF option yet, but it will be very similar to the PDF one if i can get it to work
Any and all help much appreciated.
Private Sub cmdclose_Click()
Unload Me
End Sub
Private Sub copyfromcmd_Click()
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
'.InitialFileName = Application.GetSaveAsFilename()
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
copyfromtb.Value = sItem
Set fldr = Nothing
End Sub
Private Sub copytocmd_Click()
Dim fldr As FileDialog
Dim sItem2 As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
'.InitialFileName = Application.GetSaveAsFilename()
If .Show <> -1 Then GoTo NextCode
sItem2 = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem2
copytotb.Value = sItem2
Set fldr = Nothing
End Sub
Private Sub runcmd_Click()
Dim R As Range
Dim SourcePath As String, DestPath As String, FName As String
'Setup source and dest path (Note: must have a trailing backslash!)
SourcePath = Me.copyfromtb.Value
DestPath = Me.copytotb.Value
'Visit each used cell in column B
For Each R In Range("B1", Range("B" & Rows.Count).End(xlUp))
'Search the file with the file mask from the cell (Note: can contain wildcards like *.xls)
FName = Dir(SourcePath & R.Value & ".pdf")
'Loop while files found
Do While FName <> ""
'Copy the file
FileCopy SourcePath & FName, DestPath & FName
'Search the next file
FName = Dir()
Loop
Next
MsgBox ("PDF's Copied")
End Sub
Expected Results:
When the Copy Files command button is clicked, the pdf files from part numbers listed in column B will be copied from the first folder location to the second folder location.
If the entries are blank a message should appear which will request folder location are selected
Once the PDF's have been moved a message should appear to tell the user the number of files which have been copied.
Actual Results:
The folder location is being entered into the required textbox, but the PDF's are not being copied over
try this
dim counter as integer
counter = 0
'Visit each used cell in column B
For Each R In Range("B1", Range("B" & Rows.Count).End(xlUp))
'Search the file with the file mask from the cell (Note: can contain wildcards like *.xls)
FName = Dir(SourcePath & R.Value & ".pdf")
'Loop while files found
Do While FName <> ""
counter = counter + 1
'Copy the file
FileCopy SourcePath & FName, DestPath & FName
'Search the next file
FName = Dir()
Loop
Next
MsgBox (counter & " PDF's Copied")
good luck
I just realized my error
I need to add the trailing backslash!
SourcePath = Me.copyfromtb.Value
DestPath = Me.copytotb.Value
Changed to
SourcePath = copyfromtb.Value & "\"
DestPath = copytotb.Value & "\"
Still having issues with counting the number of moved files and adding that value to the message box at the end
I have vba code to convert a ppt to pptx file, but how do I preserve the file properties (author/created date, modified date, etc)? Here is the vba code that converts the, in this case .ppt file, to a pptx file.
Sub BatchSave()
' Opens each PPT in the target folder and saves as PowerPoint 2007/2010 (.pptx) format
Dim sFolder As String
Dim sPresentationName As String
Dim oPresentation As Presentation
Dim bidpList As Collection
' Select the folder:
Set fDialog = Application.FileDialog(msoFileDialogFolderPicker)
With fDialog
.Title = "Select folder and click OK"
.AllowMultiSelect = False
.InitialView = msoFileDialogViewList
If .Show <> -1 Then
MsgBox "Cancelled By User", , "List Folder Contents"
Exit Sub
End If
sFolder = fDialog.SelectedItems.Item(1)
If Right(sFolder, 1) <> "\" Then sFolder = sFolder + "\"
End With
' Make sure the folder name has a trailing backslash
If Right$(sFolder, 1) <> "\" Then
sFolder = sFolder & "\"
End If
' Are there PPT files there?
If Len(Dir$(sFolder & "*.PPT")) = 0 Then
MsgBox "Bad folder name or no PPT files in folder."
Exit Sub
End If
' Open and save the presentations
sPresentationName = Dir$(sFolder & "*.PPT")
While sPresentationName <> ""
Set oPresentation = Presentations.Open(sFolder & sPresentationName, , ,
False)
Call oPresentation.SaveAs(sFolder & sPresentationName & "x")
oPresentation.Close
Wend
MsgBox "DONE"
End Sub
Declaring object variables for your two presentations will simplify the code a bit, and then you can do something along these lines:
Dim oPres As Presentation
Dim oCopyPres As Presentation
Dim x As Long
Set oPres = ActivePresentation
ActivePresentation.SaveCopyAs "c:\temp\test.pptx"
Set oCopyPres = Presentations.Open("c:\temp\test.pptx")
On Error Resume Next
For x = 1 To oPres.BuiltInDocumentProperties.Count
oCopyPres.BuiltInDocumentProperties(x).Name = oPres.BuiltInDocumentProperties(x).Name
oCopyPres.BuiltInDocumentProperties(x).Value = oPres.BuiltInDocumentProperties(x).Value
Next
You'll want to modify this to set WithWindow false and to use variables as file names, but you're already doing that in the code you have. It should be simple enough to fold in a modified version of the code above.
Dim savepath as String
Dim dfile as String
Dim wb as Workbook
'strings setting omitted
If Not Dir(savepath & dfile) <> "" Then
MsgBox "Cannot find the file."
End If
Set wb = Workbooks(savepath & dfile)
wb.Open
'Workbooks(savepath & dfile).Open also fails
I'm getting a run-time error 9 despite the Dir() not raising the messagebox. I can copy and paste the concatenated string into Windows Explorer bar and the excel file opens, so the file certainly exists.
Any ideas?
Workbooks only includes open workbooks. To open a workbook you use Workbooks.Open(pathToFile)
Dim savepath as String
Dim dfile as String
Dim wb as Workbook
'strings setting omitted
If Dir(savepath & dfile) = "" Then
MsgBox "Cannot find the file."
Else
Set wb = Workbooks.Open(savepath & dfile)
End If
i would suggest changing your code mainly in the if condition to:
Dim savepath as String
Dim dfile as String
Dim wb as Workbook
'strings setting omitted
strFilename = Dir(savepath & dfile)
If Len(strFilename) > 0 Then
Set wb = Workbooks.Open(savepath & dfile)
Else
MsgBox "Cannot find the file " & dfile & " in " & savepath & "."
End If
This way you also assure, that Open only happens when file actually exists and i think putting the positive case on top and the error on bottom is more readable.
you could also write
If Dir(savepath & dfile) <> "" Then
but for a quick brief review of code, something like NOT fn() <> "" is not as understandable
Okay here it is. I've done a bunch of coding in the last 3 or 4 months, learned a lot, BUT, I can't figure out why this code STILL opens a file when I hit cancel at the end once the popup window comes up showing my filtered filenames. Any advice would be highly appreciated.
Sub OpenByPartialName()
' Returns popup window with only filtered filenames matching
' Partial Filename input
Dim WB As Workbook
Dim Ans As String
Dim MyFile As String
Dim path As String
' Folder Path Name for Forms
path = ("S:\Forms Folder\")
Ans = InputBox("Enter Partial filename Filter", "Open File With Partial Name Filter")
MyFile = Dir("S:\Forms Folder\" & "*" & Ans & "*.xls")
MyFilter = path & "*" & Ans & "*.xls"
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.InitialFileName = MyFilter
If .Show = 1 Then
MyFile = .SelectedItems(1)
End If
End With
On Error Resume Next
Set WB = Workbooks.Open(MyFile)
End Sub
That would be a dirty hack, but if you had an Else branch here:
If .Show = 1 Then
MyFile = .SelectedItems(1)
Else
MyFile = vbNullString
End If
...the code that actually opens the file could verify whether MyFile is empty or not before trying:
On Error Resume Next
If MyFile <> vbNullString Then Set WB = Workbooks.Open(MyFile)
That said I think you should be handling at least error 53 ("file not found") here, instead of just shoving all errors under the carpet.
Also the WB reference isn't used. Perhaps the Sub should be a Function that returns the opened workbook, or Nothing if opening fails?
This is what I use to select a directory. If the function returns an empty string, I don't try to open the file.
Private Function FolderPicker() As String
'*******************************************
' returns directory path to be printed to
' does not allow multiple selections,
' so returning the first item in selected
' items is sufficient.
'
' returns empty string On Error or if the
' user cancels
'********************************************
On Error GoTo ErrHandler
Const DefaultDirectory As String = "C:Path\to\default\directory\"
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = "Choose Directory to Print to"
.InitialFileName = DefaultDirectory
.InitialView = msoFileDialogViewSmallIcons
If .Show <> -1 Then
FolderPicker = vbNullString
Else
FolderPicker = .SelectedItems(1)
End If
End With
Exit Function
ErrExit:
FolderPicker = vbNullString
Exit Function
ErrHandler:
MsgBox "Unexpected Error: " & Err.number & vbCrLf & "Source: " & Err.Source & _
"Description: " & Err.Description, vbCritical, "ERROR!"
Resume ErrExit
End Function
So, you would call it like this.
MyFile = FolderPicker
If MyFile <> vbNullString Then
Set WB = Workbooks.Open(MyFile)
End If
Much blood, sweat and tears later (Serious web surfing, cobbling code together and retesting) I have found an answer that works without any problems for pressing 'Cancel' at any point.
Sub OpenAuditPartialName()
' Returns popup window with only filtered
' filenames matching input criteria.
' Filenames are saved from another code that uses 3 variables to generate a _
' filename 'Filename part1_Filename part2_Filename part3 Forms.xls'
Dim WB As Workbook
Dim Ans As String
Dim MyFile As String
Dim path As String
' Folder path for Forms
path = ("S:\Forms Folder\")
Ans = InputBox("Enter any part of the filename to search by." & vbCrLf & vbCrLf & _
"Full or Partial information is OK." & vbCrLf & vbCrLf & "Filename part1" _
& vbCrLf & "Filename part2" & vbCrLf & "Filename part3", "Enter Partial Filename Filter")
' Exits on 'Cancel' as it should
If Ans = "" Then
Exit Sub
End If
MyFile = Dir(path & "*" & Ans & "*.xls")
MyFilter = path & "*" & Ans & "*.xls"
'*******************************************
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.InitialFileName = MyFilter
' Now accepts the 'Cancel' instead of continuing to open the first file
' in the filtered list when pressed
If .Show = 0 Then
ElseIf Len(Ans) Then
MyFile = .SelectedItems(1)
On Error Resume Next
Set WB = Workbooks.Open(MyFile)
Else
Exit Sub
End If
'*******************************************
End With
End Sub