I am trying to have a browse button on an excel sheet by clicking which i can select a file and the path of the selected file will get displayed in a textbox on the same excel sheet.This is the code i have tried:
Dim File_Path As Long
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
GetFolder = .SelectedItems(1)
TextBox1.Value = GetFolder
End With
End Sub
when i run the code,i am able to select a file but then i am getting a runtime error "object required" and the line
TextBox1.Value = GetFolder
is getting highlighted.can anyyone please help me with this.thank you.
Error suggest that you don't have any TextBox object in the Activesheet or Object reference is not complete.
Possible solution (when talking about ActiveSheet):
ActiveSheet.TextBox1.Value = GetFolder
or when talking about any other sheet:
Sheets("NameOfTheSheetHere").TextBox1.Value = GetFolder
Misunderstood the question.
Here is another way.
Replace
TextBox1.Value = GetFolder
with
ActiveSheet.Shapes("Textbox1").OLEFormat.Object.Object.Text = getfolder
In a more structured way...
Sub Button2_Click()
Dim File_Path As Long
Dim shp As Shape
Set shp = ActiveSheet.Shapes("Textbox1")
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
getfolder = .SelectedItems(1)
shp.OLEFormat.Object.Object.Text = getfolder
End With
End Sub
Also instead of Application.FileDialog(msoFileDialogOpen) you may use the inbuilt Application.GetOpenFilename
Private Sub CommandButton1_Click()
Dim Ret
Ret = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*")
If Ret <> False Then _
ActiveSheet.Shapes("Textbox1").OLEFormat.Object.Object.Text = getfolder
End Sub
BTW change "Excel Files (*.xls*), *.xls*" to "All Files (*.*), *.*" if you want to show all files and not just Excel Files.
Related
I am trying to give users the option to 'set' a default folder location, this would only be used to prefill further userform text boxes to save time having to go through the msoFileDialogFolderPicker
I did use chdir, but that was written into the vba script, this location will differ from user to user and should only need to be set once upon addon installation
This is the code for the master folder selector:
Private Sub cmdfoldsel_Click()
On Error GoTo err
Dim fileExplorer As FileDialog
Set fileExplorer = Application.FileDialog(msoFileDialogFolderPicker)
'To allow or disable to multi select
fileExplorer.AllowMultiSelect = False
With fileExplorer
If .Show = -1 Then 'Any folder is selected
tbmasterloc.text = .SelectedItems.Item(1)
Else ' else dialog is cancelled
MsgBox "You have cancelled the dialogue"
[folderPath] = "" ' when cancelled set blank as file path.
End If
End With
err:
Exit Sub
End Sub
It is letting me choose the folder, but obviously the text disappears when I close ( I was using a close button with unload me but i thought that was deleting the text
An example of the second userform which will call that folder location is here:
Private Sub UserForm_Initialize()
copyfromtb.Value = mfs.tbmasterloc.text
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
I want to import a txt file to excel using a button.
I have a dialog box to pick a folder name and display the name of the folder that the user selects.
If the user selects cancel an error occure because of type mismatch. I have declared variables as VARIANT
Have a look in the code:
Sub ImportTXTFiles()
Dim fso As Object
Dim xlsheet As Worksheet
Dim qt As QueryTable
Dim txtfilesToOpen As Variant, txtfile As Variant
Application.ScreenUpdating = False
Set fso = CreateObject("Scripting.FileSystemObject")
txtfilesToOpen = Application.GetOpenFilename(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If txtfilesToOpen = "False" Then
Exit Sub
End If
For Each txtfile In txtfilesToOpen
' FINDS EXISTING WORKSHEET
For Each xlsheet In ThisWorkbook.Worksheets
If xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "") Then
xlsheet.Activate
GoTo ImportData
End If
Next xlsheet
' CREATES NEW WORKSHEET IF NOT FOUND
Set xlsheet = ThisWorkbook.Worksheets.Add( _
After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "")
xlsheet.Activate
GoTo ImportData
My question is how can I handle this exception here
If txtfilesToOpen = "False" Then
Exit Sub
End If
if the user cancels the selection, while variables are declared as variant.
Thanks in advance.
Maybe using this auxiliar function will help you out:
Option Explicit
Sub Test()
Dim txtfilesToOpen As String
txtfilesToOpen = GetFile
End Sub
Private Function GetFile() As String
Dim fldr As FileDialog
Set fldr = Application.FileDialog(msoFileDialogFilePicker)
With fldr
.Title = "Text Files to Open"
.AllowMultiSelect = False
If .Show <> -1 Then
MsgBox "No file was picked. Please run the macro again."
End
End If
GetFile = .SelectedItems(1)
End With
End Function
If the user doesn't pick a file, a MsgBox will pop up warning the user and then finishing the whole procedure. Note that this procedure works for only one selected item at a time. If you need to pick more than one, consider using the folder picker.
I have the following code
Private Sub btnOpenTemplate_Click()
Dim c As Range
Dim fd As Office.FileDialog, directory As String, fileName As String
Set c = Settings.Range("A1")
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Âûáåðèòå øàáëîí ÏÌÈ."
.Filters.Clear
.Filters.Add "Word 2003", "*.doc?"
If .Show = True Then
fileName = .SelectedItems(1)
End If
End With
If fileName = "" Then
Exit Sub
End If
If Dir(fileName, vbNormal) <> "" Then
If c.Worksheet.OLEObjects.Count > 0 Then
c.Worksheet.OLEObjects(1).Delete
End If
Settings.OLEObjects.Add fileName:=fileName, Link:=False, DisplayAsIcon:=True
End If
Settings.Range("A2").Value = fileName
lblTemplateFile.Caption = fileName
End Sub
Whenever it is executed, the workbook gets damaged and Excel is unable to repair and save it. What could be wrong? What I mean is that the workbook works fine just until I embed an object (Word doc) into it via the macro. Then it gets damaged.
I have written code for opening a PPT presentation on my system and store only the ppt file name in a variable. That ppt file will call one more saved module. My code is given below:
Sub PPTTest()
Dim PPT As Object
Set PPT = CreateObject("PowerPoint.Application")
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogOpen)
With fldr
.Title = "Select a File"
.AllowMultiSelect = False
.InitialFileName = ""
If .Show <> -1 Then Exit Sub
sItem = .SelectedItems(1)
End With
Set fldr = Nothing
PPT.Presentations.Open sItem, , , False
Filename = Mid$(sItem, InStrRev(sItem, "\") + 1, Len(sItem))
PPT.Run "fileName!Module1.KillSpecificSlide"
End Sub
But after debugging in the line
PPT.Run "fileName!Module1.KillSpecificSlide"
it shows the error
Invalid request. Sub or function not defined.
When I have written the same code as
PPT.Run "BOD.pptx!Module1.KillSpecificSlide"
it works fine. But when I store the same name in a variable and pass it through the code its shows error.
How to resolve this issue?
I am trying to accomplish the following in a access VBA code:
Select a file from a folder
Convert the file from .csv to .xlsx
Import that file into a table in my Access database
I am having trouble with the last step, I am able to covert the file but on import there seems to be an issue with the file format. Getting the following error: " Run-time error'3274' "External table is not in the expected format"
Does anyone know of a possible solution?
Code:
Private Sub Command1_Click()
Dim fd As Office.FileDialog
Dim varFile As Variant
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Title = "Choose the File you would like to import"
.AllowMultiSelect = False
.InitialFileName = "Z:\location\"
.Filters.Clear
.Filters.Add "Excel Files", "*.xls*"
.Filters.Add "All Files", "*.*"
.Filters.Add "CSV Files", "*.csv"
If .Show = True Then
For Each varFile In .SelectedItems
Dim xlApp As Object
Dim wb As Object
Dim strFile As String
Set xlApp = CreateObject("Excel.Application")
strFile = varFile
Set wb = xlApp.Workbooks.Open(strFile)
With wb
' where 56 is value of excel constant xlExcel8
.SaveAs FileName:=Replace(strFile, ".csv", ".xlsx"), FileFormat:=51
End With
'clean up
Set wb = Nothing
xlApp.Quit
Set xlApp = Nothing
MsgBox ("Your File has been converted and is currently being imported to this database") 'Should come up as a success
DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadsheetType:=acSpreadsheetTypeExcel9, _
TableName:="C-Report", _
FileName:=varFile, _
HasFieldNames:=True
MsgBox ("Your Import has been complete") 'Should come up as a sucess message
Next
Else
'stop execution if nothing selected
MsgBox ("There has been an error with your import. Please try again.")
End
End If
End With
End Sub
In the TransferSpreadsheet, the name of the csv file is being referenced instead of the xlsx file.
Add this line just before that statement:
varFile = Left(varFile, (InStrRev(varFile, ".", -1, vbTextCompare) - 1)) & ".xlsx"
It will then see the proper filename and complete the transfer successfully.