Save as txt with name and file location based on cell value - vba

i need to export as txt some sheets , i can't do it . I try it in that way but don't go to the right file location :
Dim filePath As String
Dim fileName As String
filePath = Sheet1.Range("B3").Value
fileName = Sheet22.Range("N3").Value
Sheet14.Select
ActiveWorkbook.SaveAs fileName:= _
fileName,
FileFormat:= _
xlText, CreateBackup:=False
it's that correct ?

Unless you want to rename your current worksheets all the time you save them you should try this:
Dim ws As Excel.Worksheet
Dim fileName As String
Sub Export_WS()
Set ws = Worksheets("Exportsheet")
'Get file path your way by this Sub
GetFile
'Copy the ws to a new workbook
ws.Copy
'With the new wb:
With Workbooks(Workbooks.Count)
'Save and close the new workbook
.SaveAs fileName:=fileName, FileFormat:=xlTextPrinter
.Close False
End With
End Sub
Here is how I got the file link
Function GetFile() As String
Dim filename_path As Variant
filename_path = Application.GetOpenFilename(FileFilter:="xyz* (*.txt), *.txt", Title:="Select file")
If filename_path = False Then Exit Function
GetFile = filename_path
fileName = filename_path
End Function
Hope that helps.
Or like you suggested by a Cell Value
fileName = SheetXYZ.Range("A1").Value
Of course you can also assign the filename manually:
fileName = "c:filename.txt"
Additional Information is here:
File Operations

Related

Import CSV file with partial name in vba

First, let me brief scenario. I want to Import specific CSV file from the user-provided location. I am able to Import it with Fix file name.
Now, I want to Import a CSV file which changing one file name each time.
E.g.
Newdata_Files_LMBN_124587
Newdata_Files_LMBN_458965
Newdata_Files_LMBN_134654
Newdata_Files_LMBN_894354, etc...
I have written code for it, but it doesn't work
Sub zzandand(Optional opt As String)
Application.ScreenUpdating = False
Dim compd1, compd2 As String
Dim ws As Worksheet
Dim rng As Range
Dim path As Variant
Dim tfr1, tfr2 As String
Set path = UserForm1.TextBox1
compd1 = path & "\" & Newdata_Files_ & "*" & ".csv"
If Dir(compd1, vbDirectory) = vbNullString Then
MsgBox ("The file Newdata_Files(csv) could not be found")
Unload UserForm1
End
Else
Workbooks.Open (compd1)
ActiveSheet.Activate
Sheets.Copy Before:=ThisWorkbook.Sheets(Sheets.Count)
ActiveSheet.Name = "compd2"
tfr1 = ActiveSheet.Range("A1").Value
ActiveSheet.Range("A1").Value = UCase(tfr1)
Workbooks("compd1").Close
End If
Application.ScreenUpdating = True
End Sub
Untested:
Sub zzandand(Optional opt As String)
Dim compd1 As String
Dim ws As Worksheet, wb As Workbook
Dim path As Variant
path = Trim(UserForm1.TextBox1)
If Right(path, 1) <> "\" Then path = path & "\" '<<< ensure trailing "\"
compd1 = Dir(path & "Newdata_Files_*.csv") '<<< any matches?
If Len(compd1) = 0 Then '<<< no need for Dir here....
MsgBox "The file Newdata_Files(csv) could not be found"
Unload UserForm1
Else
Set wb = Workbooks.Open(path & compd1) '<<< use the full path!
wb.Sheets(1).Copy _
Before:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
wb.Close False 'close without saving
Set ws = ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
ws.Name = "compd2"
ws.Range("A1").Value = UCase(ws.Range("A1").Value)
End If
End Sub

VBA to Save in New Directory Depending on Sheet Name

I am trying to prepare a code that opens all files in a folder, checks the name of the sheet in the opened file and, depending on the name of that sheet, re-saves it in to a new folder. However, when I'm trying to add the IF statement to check that the sheet name exists, it's telling me that this Method does not exist. Is anybody able to advise a more appropriate method please?
Dim MyFile As String
MyPath = "Q:\Folder Name1\Folder Name2\Folder Name3\Folder Name4\"
MyFile = Dir(MyPath)
Do While MyFile <> ""
If MyFile Like "*.xlsx" Then
Workbooks.Open MyPath & MyFile
Dim ws1 As Worksheet
Set ws1 = Sheets("Adult_Return")
If ws1.Exists Then
ChDir "Q:\Folder Name1\Folder Name2\Folder Name3\Folder Name4\Return"
ActiveWorkbook.SaveAs Filename:=MyFile & ".xlsx"
Else
ChDir "Q:\Folder Name1\Folder Name2\Folder Name3\Folder Name4\Single"
ActiveWorkbook.SaveAs Filename:=MyFile & ".xlsx"
Thanks.
Create a function:
Function SheetExists(wb As Workbook, sheetName As String)
Dim ws As Worksheet
SheetExists = False
For Each ws In wb.Sheets
If UCase(ws.Name) = UCase(sheetName) Then
SheetExists = True
Exit Function
End If
Next ws
End Function
Call it like this:
Dim wb As Workbook
Set wb = Workbooks.Open(MyPath & MyFile)
If SheetExists(wb, "Adult_Return") Then
...
Btw: You don't have to do the chdir, just put the path in the SaveAs:
wb.SaveAs "Q:\Folder Name1\Folder Name2\Folder Name3\Folder Name4\Single\" & MyFile & ".xlsx
And: Do not forget to close the workbook!

Combining macros in Excel

I'm trying to combine/nest 3 different functions in Excel VBE: open, loop, and click. I have them written out separately, but am unsure of how to combine them. I've tried the "call macro" function but got a compile error returned to me.
The goal is to open a bunch of files within a certain folder and click on the URL in all of them (the URL will not always be the same, so I need a click function that targets any unknown URL within a sheet).
Open macro:
Sub openMyfile()
Dim Source As String
Dim StrFile As String
Source = "/users/kmogilevsky/Desktop/IC_new/"
StrFile = Dir("/users/kmogilevsky/Desktop/IC_new/")
Do While Len(StrFile) > 0
Workbooks.Open Filename:=Source & StrFile
StrFile = Dir("/users/kmogilevsky/Desktop/IC_new/")
Loop
End Sub
Loop macro:
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
Set MySource = MyObj.GetFolder("/users/kmogilevsky/Desktop/IC_new/")
For Each file In MySource.Files
If InStr(file.Name, "test") > 0 Then
End If
Next file
End Sub
Click macro (this needs some work):
Private Sub CommandButton1_Click()
Call NewSub
End Sub
Sub ReadWorkbooksInCurrentFolder()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim MyPath As String
Dim strFilename As String
'Stop annoying popups while macro is running
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
'When working with many open workbooks its good to explicitly reference all workbooks, makes sure your code works and easier to read, understand and remember which workbook is which.
Set wbDst = ThisWorkbook
srcSheetName = "Data"
dstSheetName = "Results"
'I want to loop through all .xlsx files in the folder
MyPath = ThisWorkbook.Path
strFilename = Dir(MyPath & "\*.xlsx", vbNormal)
If Len(strFilename) = 0 Then
MsgBox "No workbooks found ending in .xlsx in current folder"
Exit Sub
End If
Do Until strFilename = ""
Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFilename)
Call CollectData(wbDst, wbSrc, dstSheetName, srcSheetName)
wbSrc.Close
strFilename = Dir()
Loop
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Sub CollectData(ByRef wbDst as Workbook, ByRef wbSrc as Workbook, dstSheetName as String, srcSheetName as String)
'Copy cell A1 contents in source workbook to destination workbook cell A1
wbDst.Sheets(dstSheetName).Range("A1") = wbSrc.Sheets(srcSheetName).Range("A1")
End Sub
Please edit the subroutine CollectData() so that it suits your needs, i.e. performs the click / url open. (I am not familiar with opening urls from excel, but I loop through workbooks often)
This code will open all Excel files in the IC_New folder on the desktop.
It will then look at each sheet and follow any hyperlinks that are on the sheet.
Sub Open_ClickHyperlinks()
Dim sPath As String
Dim vFiles As Variant
Dim vFile As Variant
Dim wrkBk As Workbook
Dim wrkSht As Worksheet
Dim HLink As Hyperlink
sPath = CreateObject("WScript.Shell").SpecialFolders("Desktop") & Application.PathSeparator & _
"IC_New" & Application.PathSeparator
'Return all files that have an extension starting with xls.
vFiles = EnumerateFiles(sPath, "xls*")
'Loop through each file.
For Each vFile In vFiles
'Open the file
Set wrkBk = Workbooks.Open(Filename:=vFile, UpdateLinks:=False)
With wrkBk
'Loop through each worksheet in the file.
For Each wrkSht In .Worksheets
'Loop through each hyperlink on the worksheet.
For Each HLink In wrkSht.Hyperlinks
HLink.Follow
Next HLink
Next wrkSht
.Close SaveChanges:=False
End With
Next vFile
End Sub
'Get all files in the specified folder, default to include all subfolders as well.
Public Function EnumerateFiles(sDirectory As String, _
Optional sFileSpec As String = "*", _
Optional InclSubFolders As Boolean = True) As Variant
EnumerateFiles = Filter(Split(CreateObject("WScript.Shell").Exec _
("CMD /C DIR """ & sDirectory & "*." & sFileSpec & """ " & _
IIf(InclSubFolders, "/S ", "") & "/B /A:-D").StdOut.ReadAll, vbCrLf), ".")
End Function

Cannot close open workbook object

I have a macro that opens an Excel file with test data, performs some simple formatting to the data, and then saves the data as a new file (keeping the file that was opened originally unchanged). I got everything to work up until the very last line, where I try to close the workbook I originally opened. There is some code just prior to attempting to close the original workbook, that sets a different workbook variable as the first one, then opens and closes it? I am a bit confused as to what the code is doing, but it closes the new file that the user just saved, and leaves the original data file that was opened at the beginning open. Here is my code below; can someone explain a little better what is happening when it saves and closes the workbook?
Sub Main()
'
'
'
'Define variables
Dim wBook As Workbook
Dim sBook As String
Dim ActSheet As Worksheet
Dim ActBook As Workbook
Dim CurrentFile As String
Dim NewFileType As String
Dim NewFile As String
'Get workbook filepath
sBook = Application.GetOpenFilename()
If sBook = "False" Then
End
End If
'Open Workbook
Set wBook = Workbooks.Open(sBook)
'Unrelated formatting occurs
'Save workbook as new file
Application.ScreenUpdating = False ' Prevents screen refreshing.
CurrentFile = wBook.FullName
NewFileType = "Excel Files 2007 (*.xlsx), *.xlsx,"
NewFile = Application.GetSaveAsFilename( _
InitialFileName:=NewFileName, _
fileFilter:=NewFileType)
If NewFile <> "" And NewFile <> "False" Then
wBook.SaveAs Filename:=NewFile, _
FileFormat:=xlOpenXMLWorkbook, _
Password:="", _
WriteResPassword:="", _
ReadOnlyRecommended:=False, _
CreateBackup:=False
Set ActBook = wBook
Workbooks.Open CurrentFile
ActBook.Close
End If
Application.ScreenUpdating = True
wBook.Close
End Sub
When you .SaveAs the wBook object becomes the "new file." You can just close that and be fine. If you wanted to create a new object leaving the original object unchanged you would use Workbook.SaveAsCopy instead.
So, what is happening in your code:
wBook.SaveAs
causes wBook to be the "new file" and the "old file is automatically closed"
Set ActBook = wBook
is basically creating two "new file" objects.
The old file is then opened using
Workbooks.Open CurrentFile
And then,
ActBook.Close
closes both wBook AND ActBook.
wBook.Close
tries to close an already closed workbook and throws an error. (Because it was the same as ActBook.)
I believe your intention is the following:
Sub Main()
'
'
'
'Define variables
Dim wBook As Workbook
Dim sBook As String
Dim ActSheet As Worksheet
Dim ActBook As Workbook
Dim CurrentFile As String
Dim NewFileType As String
Dim NewFile As String
'Get workbook filepath
sBook = Application.GetOpenFilename()
If sBook = "False" Then
End
End If
'Open Workbook
Set wBook = Workbooks.Open(sBook)
'Unrelated formatting occurs
'Save workbook as new file
Application.ScreenUpdating = False ' Prevents screen refreshing.
CurrentFile = wBook.FullName
NewFileType = "Excel Files 2007 (*.xlsx), *.xlsx,"
NewFile = Application.GetSaveAsFilename( _
InitialFileName:=NewFileName, _
fileFilter:=NewFileType)
If NewFile <> "" And NewFile <> "False" Then
wBook.SaveAs Filename:=NewFile, _
FileFormat:=xlOpenXMLWorkbook, _
Password:="", _
WriteResPassword:="", _
ReadOnlyRecommended:=False, _
CreateBackup:=False
' wBook is now the "new file" at this point and the "old file" has been closed.
End If
Application.ScreenUpdating = True
wBook.Close ' Close the new file.
End Sub

Combining data from multiple workbooks into a master

I have been searching forums and just can't work out the issue with my code. I am very new to macros and I'm sure it's something simple, like some variable not being defined, but I can't figure it out.
I am trying to load data from multiple workbooks into a master and really need help please!
Dir for source files: C:\Test Dir\
Dir for Master: C:\Test Dir\Master\
Source filenames differ, but all end in "*FORMATTED.xlsx."
Master filename: "Payroll Master.xlsx"
Source worksheet name = "Loaded Data"
Master worksheet name = "Summary"
All SOURCE data is in A2:J106.
The top row in the source and Master files are column headers and are identical.
I am loading all data into the Master file "Summary" worksheet.
My latest error is: "Run-time error '1004': Select method of Range class failed." on the "Sheets("Loaded Data").Range("A2:J106").Select" line
This is my current code:
Sub combine_data()
'
Dim MyPath As String
Dim SumPath As String
Dim MyName As String
Dim SumName As String
'Dim MyTemplate As Workbook
'Dim SumTemplate As Workbook
MyPath = "C:\Test Dir\"
SumPath = "C:\Test Dir\Master\"
MyTemplate = "*.xlsx" 'Set the template.
SumTemplate = "Payroll MASTER.xlsx"
MyName = Dir(MyPath & MyTemplate) 'Retrieve the first file
SumName = Dir(SumPath & SumTemplate)
Do While MyName <> ""
Workbooks.Open MyPath & MyName
Sheets("Loaded Data").Range("A2:J106").Select
Selection.Copy
Workbooks.Open SumPath & SumName
Sheets("Summary").Select
Range("A65536").End(xlUp).Offset(1, 0).Activate
Selection.PasteSpecial Paste:=xlPasteValues
Workbooks(MyName).Close SaveChanges:=False 'close
Workbooks(SumName).Close SaveChanges:=True
MyName = Dir 'Get next file
Loop
End Sub
Thank you!
To reduce bugs, you should state Option Explicit at the top of the module. You will then be told when using variables that are not declared and you reduce the risk of misspelling the names of variables.
You should put the SumName = Dir(SumPath & SumTemplate) just before the loop, as the Dir at the end of your Do While ... Loop will refer to the LAST Dir that had parameters. When getting past the error with the Select that you describe, you have ran into this problem.
Inside your loop, you should refer to each workbook/worksheet individually, to clarify what you are doing (helping yourself for the future).
You are opening and closing the MASTER file for every source-file. You could open it before the Loop and close it after. This will make your script faster.
Here is the code modified with the above comments:
Option Explicit
Sub combine_data()
'
Dim MyPath As String
Dim SumPath As String
Dim MyName As String
Dim SumName As String
Dim MyTemplate As String
Dim SumTemplate As String
Dim myWS As Worksheet
Dim sumWS As Worksheet
'Define folders and filenames
MyPath = "C:\Test Dir\"
SumPath = "C:\Test Dir\Master\"
MyTemplate = "*.xlsx" 'Set the template.
SumTemplate = "Payroll MASTER.xlsx"
'Open the template file and get the Worksheet to put the data into
SumName = Dir(SumPath & SumTemplate)
Workbooks.Open SumPath & SumName
Set sumWS = ActiveWorkbook.Worksheets("Summary")
'Open each source file, copying the data from each into the template file
MyName = Dir(MyPath & MyTemplate) 'Retrieve the first file
Do While MyName <> ""
'Open the source file and get the worksheet with the data we want.
Workbooks.Open MyPath & MyName
Set myWS = ActiveWorkbook.Worksheets("Loaded Data")
'Copy the data from the source and paste at the end of Summary sheet
myWS.Range("A2:J106").Copy
sumWS.Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues
'Close the current sourcefile and get the next
Workbooks(MyName).Close SaveChanges:=False 'close
MyName = Dir 'Get next file
Loop
'Now all sourcefiles are copied into the Template file. Close and save it
Workbooks(SumName).Close SaveChanges:=True
End Sub