Why am I getting object not set error? Seems to be on this line with debug?
xlsmTarget.VBProject.VBComponents.Import "C:\New Name Test\Testv3\CreateUniqueContainers.bas"
However target seems to be set, what have I done wrong?
Sub ConvertXLSFilesToXLSM()
Dim Path As String
Dim DestPath As String
Dim xlsmTarget As Workbook
Const ModulePath As String = "C:\New Name Test\Testv3\CreateUniqueContainers.bas"
Path = "C:\New Name Test\Testv3\Files\"
DestPath = "C:\New Name Test\Testv3\Files\"
WorkFile = Dir(myPath & "*.xls")
Do While WorkFile <> ""
If Right(WorkFile, 4) <> "xlsm" Then
Workbooks.Open Filename:=Path & "\" & WorkFile
ActiveWorkbook.SaveAs Filename:= _
DestPath & WorkFile & ".xlsm",
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
xlsmTarget.VBProject.VBComponents.Import ModulePath
ActiveWorkbook.Save
ActiveWorkbook.Close
End If
WorkFile = Dir()
Loop
End Sub
Option Explicit
Sub ConvertXLSFilesToXLSM()
Const FOLDER = "C:\New Name Test\Testv3\"
Const MODNAME = "CreateUniqueContainers.bas"
Dim SrcPath As String, DestPath As String
Dim SrcFile As String, DestFile As String
Dim n As Long
SrcPath = FOLDER & "Files\"
DestPath = FOLDER & "Files\"
SrcFile = Dir(SrcPath & "*.xls*")
Do While SrcFile <> ""
If Right(SrcFile, 4) <> "xlsm" Then
Debug.Print SrcFile
Workbooks.Open Filename:=SrcPath & "\" & SrcFile
' replace .xls or .xlsx with .xlsm
DestFile = DestPath & Split(SrcFile, ".")(0) & ".xlsm"
' save with new name
With ActiveWorkbook
.SaveAs Filename:=DestFile, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
CreateBackup:=False
' import module and save
.VBProject.VBComponents.Import FOLDER & MODNAME
.Save
.Close
End With
n = n + 1
End If
SrcFile = Dir()
Loop
MsgBox n & " files created", vbInformation
End Sub
You need to actually set your variable, and use it. Also, don't rely on Active*
Sub ConvertXLSFilesToXLSM()
Dim Path As String
Dim DestPath As String
Dim xlsmTarget As Workbook
Const ModulePath As String = "C:\New Name Test\Testv3\CreateUniqueContainers.bas"
Path = "C:\New Name Test\Testv3\Files\"
DestPath = "C:\New Name Test\Testv3\Files\"
WorkFile = Dir(Path & "*.xls")
Do While WorkFile <> ""
If Right(WorkFile, 4) <> "xlsm" Then
Set xlsmTarget = Workbooks.Open(Path & WorkFile)
xlsmTarget.SaveAs _
Filename:=DestPath & replace(WorkFile, ".xls", ".xlsm"), _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
CreateBackup:=False
xlsmTarget.VBProject.VBComponents.Import ModulePath
'xlsmTarget.Save
xlsmTarget.Close, True
End If
WorkFile = Dir()
Loop
End Sub
Related
I have this code.
This code converts to xlsm files.
I want to convert to xlsx files.
How?
I tried by changing
wBook.SaveAs XlsFolder & Replace(fname, ".csv", ""), ThisWorkbook.FileFormatTO
wBook.SaveAs XlsFolder & Replace(fname, ".csv", ".xlsx")
It didn't worked.
Private Sub CommandButton2_Click()
Dim CSVfolder As String
Dim XlsFolder As String
Dim fname As String
Dim wBook As Workbook
CSVfolder = "C:\csv\"
XlsFolder = "C:\Charts\"
fname = Dir(CSVfolder & "*.csv")
Do While fname <> ""
Set wBook = Workbooks.Open(CSVfolder & fname, Format:=6, Delimiter:=",")
wBook.SaveAs XlsFolder & Replace(fname, ".csv", ""), ThisWorkbook.FileFormat
wBook.Close False
fname = Dir
Loop
End Sub
Using the macro recoder, the file format for an xlsx workbook is FileFormat:=xlOpenXMLWorkbook
So here is your code :
Private Sub CommandButton2_Click()
Dim CSVfolder As String, _
XlsFolder As String, _
fname As String, _
wBook As Workbook
CSVfolder = "C:\csv\"
XlsFolder = "C:\Charts\"
fname = Dir(CSVfolder & "*.csv")
Do While fname <> ""
Set wBook = Workbooks.Open(CSVfolder & fname, Format:=6, Delimiter:=",")
wBook.SaveAs XlsFolder & Replace(fname, ".csv", ""), xlOpenXMLWorkbook
wBook.Close False
fname = Dir
Loop
End Sub
I have this code to process from a directory all the xls and xlsx and convert them to txt delimited columns and works fine:
Public Sub Save_Workbooks_As_Tabbed()
Dim folderPath As String
Dim fileName As String
Dim p As Long
folderPath = "C:\Users\user\Desktop\catalogsales\"
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
Application.ScreenUpdating = False
fileName = Dir(folderPath & "*.xls*")
Do While fileName <> vbNullString
Workbooks.Open folderPath & fileName
p = InStrRev(fileName, ".") - 1
ActiveWorkbook.SaveAs fileName:=folderPath & Left(fileName, p) & ".txt", FileFormat:=xlText, CreateBackup:=False
ActiveWorkbook.Close False
fileName = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Done"
End Sub
However I want to convert to txt delimited columns only from each file processed the sheet called “DATASHE21”. Inside each file I have a lot of sheets but I want that one only converted to text. Now the script what does is convert to tax delimited columns the first sheet but I don’t want that. I want only converted the “DATASHE21”. What would be needed to modify in the script for that?
Thank you
Please, replace this code part:
fileName = Dir(folderPath & "*.xls*")
Do While fileName <> vbNullString
Workbooks.Open folderPath & fileName
p = InStrRev(fileName, ".") - 1
ActiveWorkbook.SaveAs fileName:=folderPath & Left(fileName, p) & ".txt", FileFormat:=xlText, CreateBackup:=False
ActiveWorkbook.Close False
fileName = Dir
Loop
with this one:
Dim wb As Workbook
fileName = Dir(folderPath & "*.xls*")
Do While fileName <> vbNullString
Set wb = Workbooks.Open(folderPath & fileName)
p = InStrRev(fileName, ".") - 1
wb.Sheets("DATASHE21").Copy 'it creates a new workbook with a single sheet
ActiveWorkbook.saveas fileName:=folderPath & left(fileName, p) & ".txt", FileFormat:=xlText, CreateBackup:=False
ActiveWorkbook.Close False: wb.Close False
fileName = Dir
Loop
I want to run through a specific sheet (from & to) save those ws as a new file in a folder, if the folder doesn't exist then create.
I'm able to do it to one sheet.
ActiveSheet.Next.Select
If Range("F3").Value = "" Then
Windows("Import OT.xlsm").Activate
Sheets("Cash").Select
Dim filename101 As String
Dim path101 As String
Application.DisplayAlerts = False
path101 = Environ("UserProfile") & "\Dropbox\A271\5 Oppgjor\" & 2020 & "\"
filename101 = Range("B1").Value & ".xlsx"
ActiveWorkbook.SaveAs path101 & Range("A2") & "\" & Range("A1") & " " & filename101,xlOpenXMLWorkbook
Application.DisplayAlerts = True
Else
Cells.Select
Range("F3").Activate
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Dim Path1 As String
Dim fpathname1 As String
Path1 = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\"
fpathname1 = Path1 & Range("F3") & "\" & Range("F2") & " " & Range("B3") & ".xlsx"
path01 = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\" & Range("F3")
Dim path001 As String
Dim Folder As String
Folder = Dir(path01, vbDirectory)
If Folder = vbNullString Then
VBA.FileSystem.MkDir (path01)
ActiveWorkbook.SaveAs filename:=fpathname1, FileFormat:=51
ActiveWorkbook.Close
Sheets("Cash").Select
Else
ActiveWorkbook.SaveAs filename:=fpathname1, FileFormat:=51
ActiveWorkbook.Close
Sheets("Cash").Select
End If
End If
End Sub
I want this as a loop is because I have a few tens of sheets. For it to work I think I need to write it specific time, but with loop I learned I don't need to do that.
Excel file sheet
https://onedrive.live.com/view.aspx?resid=AF6FF2618C09AC74!29027&ithint=file%2cxlsx&authkey=!AHcJjYCu8D0NTNY
According to your comment where you wrote the steps:
Read the comments
Try to run the code using F8 key and see where you need to change it.
As you're learning, please note to first write the steps in plain English Norsk and then develop your code.
See how I just followed your steps with readable code.
Code:
Public Sub GenerateCustomersFiles()
' 1) Active sheet (oppgjør 1-20)
Dim targetSheet As Worksheet
For Each targetSheet In ThisWorkbook.Sheets
' Check only sheets with string in name
If InStr(targetSheet.Name, "Oppgjør") > 0 Then
' 2) look if value in F3 is empty
If targetSheet.Range("F3").Value = vbNullString Then
' 3) if it is, do select "cash" sheet and save this file (its name and path are given above what it should be named)
Dim fileName As String
Dim filePath As String
Dim folderPath As String
folderPath = Environ("UserProfile") & "\Dropbox\A271\5 Oppgjor\" & 2020 & "\"
fileName = targetSheet.Range("B1").Value & ".xlsx"
filePath = folderPath & targetSheet.Range("A2") & "\" & targetSheet.Range("A1") & " " & fileName
ThisWorkbook.Worksheets("Cash").Select
ThisWorkbook.SaveAs filePath, xlOpenXMLWorkbook
Else
' 4) if it doesn't, do open selected sheet to a new workbook and save that in clients name folder (folder and path given above in code section)
folderPath = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\" & targetSheet.Range("F3")
fileName = targetSheet.Range("F2") & " " & targetSheet.Range("B3") & ".xlsx"
filePath = folderPath & "\" & fileName
' 5) check if clients folder exist or not for the file to be saved in.
' if folder doesnt exist,
' create new and save file there.
CreateFoldersInPath folderPath
' if folder exist just save the file there
Dim targetWorkbook As Workbook
Set targetWorkbook = Workbooks.Add
targetSheet.Copy before:=targetWorkbook.Sheets(1)
targetWorkbook.SaveAs filePath, 51
targetWorkbook.Close
End If
End If
Next targetSheet
End Sub
' Credits: https://stackoverflow.com/a/31034201/1521579
Private Sub CreateFoldersInPath(ByVal targetFolderPath As String)
Dim strBuildPath As String
Dim varFolder As Variant
If Right(targetFolderPath, 1) = "\" Then targetFolderPath = Left(targetFolderPath, Len(targetFolderPath) - 1)
For Each varFolder In Split(targetFolderPath, "\")
If Len(strBuildPath) = 0 Then
strBuildPath = varFolder & "\"
Else
strBuildPath = strBuildPath & varFolder & "\"
End If
If Len(Dir(strBuildPath, vbDirectory)) = 0 Then MkDir strBuildPath
Next varFolder
'The full folder path has been created regardless of nested subdirectories
'Continue with your code here
End Sub
Let me know how it goes
I have a bit of code that loops through a bunch of files in a folder, runs a macro on each of them, and then saves them as a .csv file in a different folder. The process runs fine with if the destination csv folder is empty. What I want to do is skip the process if the .csv file already exists. The problem with the code below, is that the Filename = Dir() returns a null value and the loop ends if the .csv file exists. So how do I continue looping through the other files in the first folder?
Sub ProcessFiles()
Dim Filename, Pathname, strFileExists As String
Dim wb As Workbook
Application.ScreenUpdating = False
Pathname = ActiveWorkbook.Path & "\Files\"
Filename = Dir(Pathname & "*.xlsx")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
length = Len(ActiveWorkbook.Name)
Name = Left(ActiveWorkbook.Name, length - 5)
CSVName = ActiveWorkbook.Path & "\CSV Files\" & Name & ".csv"
strFileExists = Dir(CSVName)
If strFileExists = "" Then
Transform wb 'Run Transform function
wb.SaveAs Filename:=CSVName, FileFormat:=xlCSVMSDOS, CreateBackup:=False
wb.Close SaveChanges:=False
Filename = Dir()
Else
wb.Close SaveChanges:=False
Filename = Dir()
End If
Loop
End Sub
I think braX is right: the problem is you are using Dir twice. This seems to be working for me:
Sub ProcessFiles()
Dim Filename, Pathname, strFileExists As String
Dim wb As Workbook
Dim IntFileNumber As Integer
Dim IntCounter01 As Integer
Dim Length As Byte
Dim Name As String
Dim CSVName As String
Application.ScreenUpdating = False
Pathname = ActiveWorkbook.Path & "\Files\"
Filename = Dir(Pathname & "*.xlsx")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
Length = Len(ActiveWorkbook.Name)
Name = Left(ActiveWorkbook.Name, Length - 5)
CSVName = ActiveWorkbook.Path & "\CSV Files\" & Name & ".csv"
strFileExists = Dir(CSVName)
If strFileExists = "" Then
Transform wb 'Run Transform function
wb.SaveAs Filename:=CSVName, FileFormat:=xlCSVMSDOS, CreateBackup:=False
wb.Close SaveChanges:=False
Filename = Dir(Pathname & "*.xlsx")
IntFileNumber = IntFileNumber + 1
For IntCounter01 = 1 To IntFileNumber
Filename = Dir()
Next
Else
wb.Close SaveChanges:=False
Filename = Dir(Pathname & "*.xlsx")
IntFileNumber = IntFileNumber + 1
For IntCounter01 = 1 To IntFileNumber
Filename = Dir()
Next
End If
Loop
End Sub
Basically i reset the Filename and re-play Dir as many time as needed to reach the wanted file.
I've added some declarations too. You might also want to turn true the ScreenUpdating at the end of the subroutine, but that's up to you.
By clicking a button in Excel, the user exports a specific sheet to a csv with a dynamic filename and the csv is saved in a pre-determined directory.
Instead of saving to a predetermined directory, can users have the browse window to choose a directory to save to?
Sub Export()
Dim MyPath As String
Dim MyFileName As String
MyPath = "C:\importtest"
MyFileName = "MR_Update_" & Sheets("Monthly Review").Range("D3").Value & "_" & Format(Date, "ddmmyyyy")
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Sheets("Export Data").Copy
With ActiveWorkbook
.SaveAs Filename:= _
MyPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False
.Close False
End With
End Sub
Excel has an inbuilt FileSave Dialog. It is called .GetSaveAsFilename. Use that.
Syntax
expression.GetSaveAsFilename(InitialFilename, FileFilter, FilterIndex, Title, ButtonText)
Usage
Dim fileSaveName As Variant
fileSaveName = Application.GetSaveAsFilename( _
fileFilter:="Excel Files (*.csv), *.csv")
If fileSaveName <> False Then
'
'~~> Your code to save the file here
'
End If
As Patrick suggested, you're looking for the .FileDialog property.
To implement it, try this:
Sub Export()
Dim MyPath As String
Dim MyFileName As String
MyFileName = "MR_Update_" & Sheets("Monthly Review").Range("D3").Value & "_" & Format(Date, "ddmmyyyy")
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Sheets("Export Data").Copy
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = "" '<~~ The start folder path for the file picker.
If .Show <> -1 Then GoTo NextCode
MyPath = .SelectedItems(1) & "\"
End With
NextCode:
With ActiveWorkbook
.SaveAs Filename:=MyPath & MyFileName, FileFormat:=xlCSV,CreateBackup:=False
.Close False
End With
End Sub
Try This......
Sub Export()
Dim MyPath As String
Dim MyFileName As String
MyPath = "C:\importtest"
MyFileName = "MR_Update_" & Sheets("Monthly Review").Range("D3").Value & "_" & Format(Date, "ddmmyyyy")
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Sheets("Export Data").Copy
With ActiveWorkbook
.SaveAs Filename:= _
MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False
.Close False
End With
End Sub
Here's a script I've been using lately that I like a lot. Thought I would leave this here:
Sub ExportCSV()
Dim FlSv As Variant
Dim MyFile As String
Dim sh As Worksheet
Dim MyFileName As String
Dim DateString As String
DateString = Format(Now(), "yyyy-mm-dd_hh_mm_ss_AM/PM") '<~~ uses current time from computer clock down to the second
MyFileName = DateString & "_" & "Whatever you like"
Set sh = Sheets("Sheet you'd like to export")
sh.Copy
FlSv = Application.GetSaveAsFilename(MyFileName, fileFilter:="CSV (Comma delimited) (*.csv), *.csv", Title:="Where should we save this?")
If FlSv = False Then GoTo UserCancel Else GoTo UserOK
UserCancel: '<~~ this code is run if the user cancels out the file save dialog
ActiveWorkbook.Close (False)
MsgBox "Export canceled"
Exit Sub
UserOK: '<~~ this code is run if user proceeds with saving the file (clicks the OK button)
MyFile = FlSv
With ActiveWorkbook
.SaveAs (MyFile), FileFormat:=xlCSV, CreateBackup:=False
.Close False
End With
End Sub