Excel 2016 Macro Unable to Find File : Runtime Error 1004 - vba

I am running into issues while attempting to open an additional Excel file using VBA in Excel 2016. It matters not whether the file is in the same directory. I am thinking it has something to do with a default setting in Excel 2016 that is blocking the search? The Macro functioned in Excel 2010.
Private Sub CommmandButton_Click()
Dim source As String
Dim temp As Workbook
source = InputBox("Enter source")
Set temp = Workbooks.Open(source)
end sub

Here is an example solution using the FileDialog object
Private Sub CommmandButton_Click()
Dim fDialog As FileDialog, _
wb As Excel.Workbook
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Title = "Select a file"
.InitialFileName = "C:\"
.Filters.Clear
' Prevent Error by specifying that the user must use an excel file
.Filters.Add "Excel files", "*.xlsx,*.xls,*.xlsm"
End With
If fDialog.Show = -1 Then
Set wb = Excel.Workbooks.Open(fDialog.SelectedItems(1))
Else
End ' Cleanly exit the Macro if the user cancels
End If
End Sub

You are allowing users to do more than point and click. This is asking for trouble. Instead:
Private Sub CommmandButton_Click()
Dim source As String
Dim temp As Workbook
source = Application.GetOpenFilename()
Set temp = Workbooks.Open(source)
end sub
This code can be further enhanced to:
1. pre-select the initial path
2. set the file-type(s)
3. give guidance
4. gracefully handle cancellations

Related

Excel vba user to select workbook then copy data

I have a macro that will copy data from a csv file to my excel file and works great if the file name is the same every time. That's where the problem lies: it's not the same name every time.
I need the script to allow a user to select the csv file. Then, the code to allow it to copy. This is what I have:
Sub importmix()
Worksheets("mixdata").Range("A1:P300").Clear
'## Open workbooks first:
Set X = Workbooks.Open("C:\test\mix.csv")
'## Set values between workbooks
Workbooks("2.xlsm").Worksheets("mixdata").Range("A1:K300").Value = _
Workbooks("mix.csv").Worksheets("mix").Range("C1:M300").Value
'##Close x:
X.Close False
End Sub
I think you are looking for something like this:
Sub test()
Dim intResult As Integer
Dim fD As FileDialog
Set fD = Application.FileDialog(msoFileDialogFilePicker)
With fD
.Title = "Select a Path"
.AllowMultiSelect = False
.Show
End With
importmix fD.SelectedItems(1)
End Sub
Sub importmix(path As String)
Worksheets("mixdata").Range("A1:P300").Clear
'## Open workbooks first:
Set X = Workbooks.Open(path)
'## Set values between workbooks
Workbooks("2.xlsm").Worksheets("mixdata").Range("A1:K300").Value = _
Workbooks(Dir(path)).Worksheets(Dir(Replace(UCase(path), ".csv", ""))).Range("C1:M300").Value
'##Close x:
X.Close False
End Sub
Dir(path) gives you the file name. A csv automatically opens a sheet with the name of the file without the extension so removing the .csv takes care of that.
Should be able to use:
Dim intResult as integer
'Dialogue box name
Application.FileDialog(msoFileDialogFolderPicker).Title = "Select a Path"
'The dialog is displayed to the user
intResult = Application.FileDialog(msoFileDialogFolderPicker).Show

VBA Workbook.Open(File) returns Nothing

EDIT: After lots of help and not having a clue what's going on, it worked using a different method of opening (see #JohnMuggin's help below)--so I un-commented my original code and suddenly it works.
I've only found one other instance of Workbook.Open("file") returning nothing (Link to Q). However, their problem was because of calling Workbook.Open("file") in a user-defined function (to my understanding). Here, I am calling it in a Sub, but am having the same issue and can't find a solution. I am using Excel 2013.
Private Sub CommandButton2_Click()
'Set variables
Dim wb As Workbook 'Workbook to open
Dim wbR As Worksheet 'This is the raw data on the new workbook
Dim wsL As Worksheet 'Worksheet in current file
Dim myFile As String 'File to open
Dim FilePicker As FileDialog
'Set light chain hit worksheet
Set wsL = ThisWorkbook.Worksheets(3)
'Optimizes Speed
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FilePicker = Application.FileDialog(msoFileDialogFilePicker)
'Opens folder-picking window
With FilePicker
.Title = "Select a file."
.AllowMultiSelect = False
If .Show = True Then
myFile = .SelectedItems(1)
Else: GoTo NextCode
End If
End With
'If folder is not selected
NextCode:
myFile = myFile
If myFile = "" Then GoTo ResetSettings
'Set variable equal to opened workbook
Set wb = Workbooks.Open(myFile)
The macro continues, but the last line Set wb = Workbooks.Open(myFile) sets wb as Nothing. This does not produce any errors until I call wb farther down in the code.
An earlier line, Set wsL = ThisWorkbook.Worksheets(3), also sets wsL as Nothing.
I have checked each line and values using the debugger, and have determined myFile is the proper path, file name, and extension.
If you have a copy of the workbook open (in a different folder) with the same name as the one your VBA is trying to open, it fails silently. The ActiveWorkbook solution appears to work - as you have at least one workbook open already - and that is active - but its not the one you think it is.
I imagine it it could be a common mistake - as while developing a VBA project you might have a copy of the target workbook open to check on column numbers etc.
And at the very last try this little sub. If it doesn't open your workbook then there is a problem with the path or filename
Sub opendfghj()
Dim wb As Workbook
Workbooks.Open Filename:="C:\Users\User\Desktop\Templates and Example data\Repeat Tests\file.xlsx"
Set wb = ActiveWorkbook
wb.Worksheets("Sheet1").Range("A1") = "It Works"
End Sub

Getting File Location and Name for Excel VBA

I am creating a VBA program that will copy one column from one file to another.
The current code works, but I wish to change it to where a prompt will come up and ask the user for the file location and name / extension. That input will be imported as the file location for the Workbooks.Open function and go from there.
How do I create a prompt to ask for the user to input the file location and name for the desired excel file, and have it input in the Workbooks.Open function?
Code:
Sub Macro1()
Dim wb1 As Workbook
Dim wb2 As Workbook
MsgBox "Now converting data from Incident Data to Specific Data "
'Set it to be the file location, name, and extension of the Call Data CSV
Set wb1 = Workbooks.Open("Z:\xxxx\Call Data - Copy.csv")
'Set it to be the file location of the Working File
Set wb2 = Workbooks.Open("Z:\xxxx\Working File.xlsx")
wb1.Worksheets(1).Columns("E").Copy wb2.Worksheets(1).Columns("A")
wb1.Worksheets(1).Columns("I").Copy wb2.Worksheets(1).Columns("Q")
wb1.Worksheets(1).Columns("AE").Copy wb2.Worksheets(1).Columns("R")
wb1.Worksheets(1).Columns("BD").Copy wb2.Worksheets(1).Columns("F")
wb2.Close SaveCahnges:=True
wb1.Close SaveChanges:=True
End Sub
I would go with FileDialog to select an input file:
Dim fDialog As FileDialog, result As Integer
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
fDialog.AllowMultiSelect = False
fDialog.title = "Select a file"
fDialog.InitialFileName = "C:\"
fDialog.Filters.Clear
fDialog.Filters.Add "Excel files", "*.xlsx"
'Show the dialog. -1 means a file has been successfully selected
If fDialog.Show = -1 Then
Debug.Print fDialog.SelectedItems(1)
End If
For saving you can refer to this post
EDIT:
To use it in Workbooks.Open you just do something like the following:
Dim fname As String
If fDialog.Show = -1 Then
fname=fDialog.SelectedItems(1)
Else
MsgBox("Filename selection error")
Exit Sub
End If
Set wb1 = Workbooks.Open(fname)

how to search closed excel file

I'm trying to search a closed excel file for a match then pull references relative to that match into a string which will then go into the open word doc, then repeat until all matches are found. I'm completely stuck on simply opening the excel file to access it to search to start with though.
It generates an excel process in task manager but I'm not able to reference it and I would actually expect it to open the application. I might be going about this the wrong way entirely.
Sub stringPrompt2()
'Find match
'build output
'put into word doc
'repeat
Dim sSearchString As String
Dim sSearchDirectory As String
Dim dlgFile As FileDialog
Dim vSelectedItem As Variant
Dim Loc As Excel.Range
Dim sPath As String
sSearchString = InputBox("String to search for", vbOKOnly, "Search String")
Set vSelectedItem = Application.FileDialog(filedialogtype:=msoFileDialogFilePicker)
With vSelectedItem
.AllowMultiSelect = False
.Show
End With
sPath = vSelectedItem.SelectedItems.Item(1)
Workbooks.Open sPath ' it isn't launching excel here.
End Sub
You just need to create a variable to hold the workbook reference and assign the result of the Workbooks.Open command to that variable so that you can work with it :
Dim myWorkbook As Workbook
Set myWorkbook = Workbooks.Open sPath
' Then do whatever you want with the Workbook object
MsgBox(myWorkbook.Name)

Command Button to modify cell value in unknown name open workbook

So the issue I'm having is we have a schedule program made via excel, that is set to replace all user names and shift times with "####" and where it would normally display names inputs "Contact blah blah for new version." This occured on 1/1/15. For now they can backdate their computer to a date prior to 1/1/15 and once they type a value in to any cell the worksheet runs and all their data re-appears. We have locations across the country that saves the file every two weeks to Wildcardname.xls I'm looking for a way to program a command button that finds the other random name opened workbook, goes to hidden sheet "help" and changes the value of Cell A184 to "01/01/2016" or any date I plug in. Which would remove the "####" issue and replace it with the originally inputed values. The user could then save the file and carry on.
I was browsing through various help boards and found this..prompts a user to select the workbook. This would be the workbook that needs changed.
http://www.excelforum.com/excel-programming-vba-macros/695467-copy-values-from-a-worksheet-to-another-workbook-source-workbook-name-unknown.html
Sub CopyData()
Dim DstRng As Range
Dim DstWkb As Workbook
Dim DstWks As Worksheet
Dim FileFilter As String
Dim Filename As String
Dim SrcRng As Range
Dim SrcWkb As Workbook
Dim SrcWks As Worksheet
Dim SheetName As String
SheetName = "Output Table"
FileFilter = "Excel Workbooks (*.xls), *.xls"
Filename = Application.GetOpenFilename(FileFilter, , "Open Source Workbook")
If Filename = "False" Then
MsgBox "Open Source File Canceled."
Exit Sub
End If
Set SrcWkb = Workbooks.Open(Filename)
Set SrcWks = SrcWkb.Worksheets(SheetName)
Set SrcRng = SrcWks.Range("A2:H20")
FileFilter = "Excel Workbooks (*.xls), *.xls"
Filename = Application.GetOpenFilename(FileFilter, , "Open Destination Workbook")
If Filename = "False" Then
MsgBox "Open Destination File Canceled."
Exit Sub
End If
Set DstWkb = Workbooks.Open(Filename)
Set DstWks = DstWkb.Worksheets(SheetName)
Set DstRng = DstWks.Range("A2:H20")
SrcRng.Copy Destination:=DstRng
End Sub
Can this be modified to accomplish what I want to complete?
I can't post an image yet, so here's a link to a mock up. Before shot of the program on the left, and on the right is what I want it to look like.
http://i528.photobucket.com/albums/dd330/DLN1223/mockup.jpg
Hopefully this description makes since....
Thanks in advance for your help.
This is what I use:
Dim FileToOpen As Variant
Dim WKbook as workbook
FileToOpen = Application.GetOpenFilename("Excel files (*.xlsx),*.xlsx", , "Select Workbook to Open")
If FileToOpen = False Then Exit Sub 'quit on cancel
Set Wkbook = Workbooks.Open(FileToOpen, False, False)
With this, I can the set the value I want, and save changes
Wkbook.Sheets("help").Range("A184")=#1/1/2016#
Wkbook.Close SaveChanges:=True
depending on the filetype, you may need to change Excel files (*.xlsx),*.xlsx to Excel files (*.xls),*.xls