PDA

View Full Version : Open a File from a folder Excel Vba



pratyu
06-21-2012, 09:30 PM
Hi all!!:hi:
I need a code in Excel vba to open a folder and select a file and assign that file to a variable of object type.
Please help!!
Thanks in Advance

defcon_3
06-21-2012, 10:31 PM
Play with this one.



Dim MyFolder As String
Dim MyFile As String 'enter any variable name

With Application.FileDialog(msoFileDialogFolderPicker)

If .Show = -1 Then
MyFile = Dir(.SelectedItems(1) & "\*.txt") ' edit file extension
End If

End With

pratyu
06-21-2012, 10:50 PM
Hi Defcon...

Thanx a lot for the quick reply!!

But, Indeed i need a little more help.

The code is giving an option to open a folder.
I want to select a File from that folder & assign that file to an Object type variable. Can you help me modifying the code?


Thnx a lot once again!!

defcon_3
06-21-2012, 11:18 PM
Assuming you were selecting a txtfile. This is how you assign the selected file to a variable: In this case the variable is MyFile. The selected file will be =/assigned to MyFile


MyFile = Dir(.SelectedItems(1) & "\*.txt")

pratyu
06-21-2012, 11:39 PM
The variable should be of Object type.. not a string one!!!

defcon_3
06-21-2012, 11:56 PM
Can you elaborate the scenario? What exactly are you working on?