I am converting an excel file to a text file by a macro and I want the text file's location to be the same folder as the excel worksheet's location.
My code is:
Dim strPath As String
strPath = "MyFileName.dat"
Dim fnum As Integer
fnum = FreeFile()
Open strPath For Output As #fnum
'my code
Close #fnum
When running it always goes to Documents. I tried "../MyFileName.dat" and it worked with some of the locations I tried putting the excel worksheet in but not with all.
What's the right way to do this. Thank you.
Assuming the workbook in question is the ActiveWorkbook, this will work. It get the workbook's full path with FullName and subsitutes the data file's name for for the workbook's:
Sub test()
Dim wb As Excel.Workbook
Dim strPath As String
Set wb = ActiveWorkbook
strPath = Replace(wb.FullName, wb.Name, "MyFileName.dat")
Dim fnum As Integer
fnum = FreeFile()
Open strPath For Output As #fnum
'my code
Close #fnum
End Sub
Related
I'm trying to convert a little over 200 .txt files into .xlsx files. This is the code I'm using:
Dim wb As Excel.Workbook
Dim FSO As New FileSystemObject
Dim obj_folder As Object
Dim file As Object
Dim path As String
Dim destination As String
Dim file_name As String
path = "C:\Users\ABCD\Desktop\Attributes Files\"
destination = "C:\Users\ABCD\Desktop\Attributes xlx\"
Set FSO = CreateObject("Scripting.filesystemobject")
Set obj_folder = FSO.GetFolder(path)
For Each file In obj_folder.Files
file_name = Left(file.Name, (InStrRev(file.Name, ".", -1, vbTextCompare) - 1))
Call Workbooks.OpenText(Filename:=file, DataType:=xlDelimited, Tab:=True)
Set wb = ActiveWorkbook
wb.SaveAs Filename:=destination & file_name & ".xlsx"
wb.Close savechanges:=False
Next file
When the code is finished running and I go to open the .xlsx workbook, I receive an error that states Excel cannot open the file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
I'm not sure what to do here as I know this works when I manually change one .txt file workbook to a .xlsx file type. I even recorded the macro and it more or less matches up with my code that I have here. (on one attempt I even copied down the recorded macro exactly and it still wouldn't let me open the .xlsx file after it finished.) Any help would be appreciated.
You never cite what file format you save in. You want to use xlOpenXMLWorkbook = 51
It looks like you pass the object file to the Filename paramter of open. I would use file.Name just like you do when you are building the output name.
Using a With block will gracefully handle the workbook object for you.
FSO.GetBaseName will remove the extension of the filename for you.
Dim FSO As New FileSystemObject
Set FSO = CreateObject("Scripting.filesystemobject")
Dim path As String
path = "C:\Users\ABCD\Desktop\Attributes Files\"
Dim destination As String
destination = "C:\Users\ABCD\Desktop\Attributes xlx\"
Dim file As Object
For Each file In FSO.GetFolder(path).Files
Dim file_name As String
file_name = FSO.GetBaseName(file.Name)
With Workbooks.OpenText(Filename:=file.Name, DataType:=xlDelimited, Tab:=True)
.SaveAs Filename:=destination & file_name & ".xlsx", FileFormat:=51
.Close savechanges:=False
End With
Next file
The VBA macro stops running on opening certain workbooks. When I run the code in break mode, it seems like control goes over to the newly opened workbook and there it has no instructions to follow.
I am trying to open a lot of workbooks, take a printout and close them.
I have also tried opening them in Read only mode, setting the calculation mode to manual but nothing has worked so far.
The following will work if you have a folder with all the workbooks.
This code will iterate through a series of excel files in a given folder:
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim strPath As String
Dim intLen As Integer
Dim strName As String
Dim wsSheet As Worksheet
Set objFSO = CreateObject("Scripting.FileSystemObject")
strPath = "C:\Users\username\Desktop\FolderName" 'Set path of folder with excel files
Set objFolder = objFSO.GetFolder(strPath) 'Get the folder object associated with the directory
For Each objFile In objFolder.Files 'Loop through the files in the folder
Workbooks.Open (strPath & "\" & objFile.Name)
Set wsSheet = Worksheets("Sheet1") 'Name of sheet in excel file
ActiveWorkbook.CheckCompatibility = False 'Skip compatibility check
This code will printout a pdf of the specified range on each sheet to a given path:
intLen = Len(objFile.Name) - 5 'Remove .xlsx characters from name
strName = Left(objFile.Name, intLen)
wsSheet.Range("A1:P58").ExportAsFixedFormat xlTypePDF, "C:\Users\username\Desktop\" & strName & ".pdf", , , , , , False
This code will close each file without saving and continue the loop through the folder:
Workbooks(strName).Close SaveChanges:=False 'Close excel file without saving
Next
I have written below piece of code to access a file and copy content from one file to the other. I am using excel 2007.
Sub copypaste()
Dim strFolder As String
Dim strFileName As String
Dim wb As Workbook
strFolder = "C:\Users\user\Desktop\sample\"
strFileName = Dir(strFolder & "*.xlsx")
Dim eRow
Dim a As Variant
Dim b As Variant
Do While Len(strFileName) > 0
**Set wb = Workbooks.Open(strFileName)**
a = Cells(7, 7)
b = Range("D11:F11")
ActiveWorkbook.Close
Worksheets("sheet1").Cells(7, 7) = a
Worksheets("sheet1").Cells(7, 8) = b
strFileName = Dir
Loop
End Sub
Although the file exists in the folder I get the error while opening the file. While in debug mode the variable strFileName contains the file name but still the file is not opening. I am getting the error at line "Set wb = Workbooks.Open(strFileName)"
Thanks in advance for your help!!
Workbooks.Open requires the full path to the workbook. I suspect you want:
Set wb = Workbooks.Open(strFolder & strFileName)
You need to replace all \ by double \\ in your path
Or add # in front of you string.
It is cause \ is the character for escape strings, like \n \s and so on so letter after a \ is transformed.
Try to print your path, you'll see what append.
EDIT
May also try :
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),");
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
As (gone) user user496736 stated you need to have a full path
But most of the time your path will be very long and cumbersome to type or you will not know it in advance, so the help of ActiveWorkbook.Path
Exemple with readonly just for information
Dim Alloc_WB As Workbook
Dim FileStr As String
FileStr = ActiveWorkbook.Path & "\" & "my_file.xlsx"
'workbook should be closed at start of code. Otherwise you get an error msg asking to re-open the Workbook
Set Alloc_WB = Workbooks.Open(Filename:=FileStr, ReadOnly:=True)
'...
'Other actions here...
'...
With Alloc_WB
.Close
End With
I have an Excel source workbook and I have some people that sent me other workbooks with information so I can add this info to the source workbook.
I want to know if it's possible to import these workbooks into the Source Workbook so that my records automatically update and the records that are new be added to the Source Workbook
Using this code you get all the files in the folder. which in your case would be the additional workbooks added.
Dim MyObject As Scripting.FileSystemObject
Set MyObject = New Scripting.FileSystemObject
Dim mySource As Folder
Dim myFile As Scripting.File
dim strFolder as string
strFolder = 'you folder path
dim strFilePath as string
Set mySource = MyObject.GetFolder(strFolder)
For Each myFile In mySource.Files
strFilePath = myFile.Path
Next
Once you have file paths you use this code to open to the workbooks
dim wrkBook as workbook
set wrkbook = workbooks.open(strFilePath)
Once you've opened the workbooks the rest is pretty much straight forward
youVariable = wrkbook.worksheet(1).cells(i, j)
I want to read certain excel files from a directory and then open them in excel-2007 with VBA.
Here is an example:
directory: c:\temp
file pattern: is xxxxx0123.xls (xxxxx represents the file names).
I try to use Application.FileSearch, but it won't work in Excel 2007. Does any one have good suggestions?
Thanks in advance
You can use DIR to find files matching your pattern, ie this code opens these files, grabs their path, and closes the files again
The code can be made recursive if you need to look in sub-folders
Sub GetFiles()
Dim strFolder As String
Dim strFileName As String
Dim wb As Workbook
strFolder = "C:\temp"
strFileName = Dir(strFolder & "\*123.xls")
Do While Len(strFileName) > 0
Set wb = Workbooks.Open(strFileName)
Debug.Print wb.FullName
wb.Close False
strFileName = Dir
Loop
End Sub