Current code:
Private Sub cmdsave_Click()
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("payin")
'find first empty row in database
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'copy the data to the database
With ws
.Cells(iRow, 1).Value = Me.txtlbp.Value
.Cells(iRow, 2).Value = Me.txtdollar.Value
.Cells(iRow, 3).Value = Me.txtsyp.Value
End With
'clear the data
Me.txtlbp.Value = ""
Me.txtdollar.Value = ""
Me.txtsyp.Value = ""
ActiveWorkbook.Save
Dim savedate
savedate = Date
Dim savetime
savetime = Time
Dim formattime As String
formattime = Format(savetime, "hh.MM.ss")
Dim formatdate As String
formatdate = Format(savedate, "DD-MM-YYYY")
Application.DisplayAlerts = False
If Len(Dir("D:\cashbackup\english", vbDirectory)) = 0 Then
MkDir "D:\cashbackup\english"
End If
Dim backupfolder As String
backupfolder = "D:\cashbackup\english\"
ActiveWorkbook.SaveCopyAs Filename:=backupfolder & "payin" & formatdate & " " & formattime & " " & ActiveWorkbook.Name
Application.DisplayAlerts = False
txtlbp.SetFocus
End Sub
the current code is saving a copy of the whole file to the directory "D:\cashbackup\english", which is taking a lot of space on disk (about 3.73 MB for each save click), where as saving only sheets: payin, payout and balance as values only without the formulas created previously in excel cells in the excel project file will save much space on the hard disk (not more than 20 KB for each save click)
my need:
I want the code save a new workbook containing only specific sheets: payin, payout and balance as values in the directory: "D:\cashbackup\english", with the same file naming, I mean without the user forms in sheet BOX and without the macros
Thank you in advance.
New Version, but remember: The site it's not a place to find people that make your work, but a place to find an help for writed code... Or a starting point. The macro use the open file and make:
delete the sheets not included in the "list"
remove the formulas
put all the cells in protected mode
add password to all the sheets
save with password (for Open & Modify)
remove the macro from the files (saving in Xlsx)
Code:
Application.DisplayAlerts = False
For Each xx In ActiveWorkbook.Sheets
If xx.Name = "Sheet1" Or xx.Name = "Sheet3" Then
xx.Select
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.Locked = True
ActiveSheet.Protect Password:="ShPwd", DrawingObjects:=True, Contents:=True, Scenarios:=True
Else
xx.Delete
End If
Next
tmp = " - " & Format(Date, "DD-MM-YYYY") & " - " & Format(Time, "HH-MM-SS")
ActiveWorkbook.Protect Password:="ShPwd", Structure:=True, Windows:=False
ActiveWorkbook.SaveAs Filename:="E:\0\New folder\aa" & tmp & ".xlsx", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False, Password:="Open" _
, WriteResPassword:="Modify"
ActiveWindow.Close
Application.DisplayAlerts = True
Related
Hi have been working on a method to import a text file into a specified worksheet, within a master workbook. Up until recently the file used Tab as the delimiter, which I was able to specify like so:
workbooks.open fileToOpen,,,,,,,,vbtab
now the file has switched to the use of a comma, which i have tried to specify in the line above but have been unable to get to work. im fairly new at this so not sure what my options. is there a way that I can get the code to identify the delimiter and convert based on that?
any help appreciated
copy of code :
Sub Multi_T_Import()
Dim fileToOpen, closeWorkbook, searchchar, sName As String
Dim chkFile, fileImport As Integer
Dim FinalRow As Long
Dim LastCol As Long
searchchar = "\"
'Turn off any prompts
MsgBox "Please Select Multi Token Data File" & vbNewLine & "MULTI TOKEN DATA IMPORT"
'Select the file to import
fileToOpen = Application _
.GetOpenFilename("txt Files (*.txt), *.txt")
'Option to import a different fileIf fileToOpen <> False Then
If fileToOpen <> False Then
fileImport = MsgBox("Are you sure you want to import " & fileToOpen, vbYesNo)
If fileImport = vbNo Then
MsgBox "Import of " & fileToOpen & " has been aborted"
Exit Sub
End If
End If
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.CutCopyMode = False
If fileImport = False Then Exit Sub
Workbooks.Open fileToOpen
Sheets.Select
If ActiveSheet.AutoFilterMode = True Then ActiveSheet.AutoFilterMode = False
FinalRow = Range("A" & Rows.Count).End(xlUp).Row
FinalRow = FinalRow + 1
Range("A1:V" & FinalRow).Select
Selection.Copy
Windows(MasterFileName).Activate
Sheets("Multi_Token_Report").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Columns("Q").Cut
'Columns("A").Insert
closeWorkbook = Mid(fileToOpen, InStrRev(fileToOpen, searchchar) + 1)
Workbooks(closeWorkbook).Close SaveChanges:=False
Dim oFS As Object
Set oFS = CreateObject("Scripting.FileSystemObject")
Range("X1").Select
ActiveCell.FormulaR1C1 = oFS.GetFile(fileToOpen).DateLastModified
Set oFS = Nothing
End Sub
There is a build-in function for separating things like comma, tab or else.
After you load in txt, it use the first column to store data. So, simply select all data on A column and use the build in function.
in VBA code, it is something like this, [ after opening txt in excel ]
Workbooks(NewWB).Sheets(1).Range("A1").EntireColumn.TextToColumns Destination:=Range("A1"), Comma:=True
enter image description here
My script can detect rows and column in first round but in the second round cannot detect rows and column.
It shows
"run-time error '1004' : "\" could not be found.
Is there some missing code or is the sequence I put wrong?
Sub Conso()
' Get common values, eg. path, date
Call getValues
Workbooks("Daily Reporting Template.xlsm").Activate
Worksheets("Master").Activate
'Open Staff Input Value
Dim i As Integer
'Dim j As Long
'j = Cells(Rows.Count, 13).End(xlUp).Row
For i = 7 To 30
StaffPath = Cells(i, 4).Value
Ws = Cells(i, 3).Value
THPath = Cells(3, 2).Value
wrkFold = Cells(2, 2).Value
Filename = Cells(4, 2).Value
'Open Template
'Workbooks.Open Filename:= _
' wrkFold & "Master TH\Template\Daily Reporting Template.xlsm", UpdateLinks:=3
Windows("Daily Reporting Template.xlsm").Activate
Workbooks.Open Filename:= _
StaffPath & "\" & Filename & ".xlsm", UpdateLinks:=3
Cells.Select
Selection.Copy
Windows("Daily Reporting Template.xlsm").Activate
Sheets(Ws).Activate
Cells.Select
ActiveSheet.Paste
ActiveWorkbook.SaveAs Filename:= _
THPath & "Daily Reporting Template" & ".xlsm" _
, FileFormat:=xlOpenXMLWorkbookMacroEnabled, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
Application.DisplayAlerts = False
Windows(Filename & ".xlsm").Close
Next i
End Sub
Your code picks the value based on active sheet. This causes issues during Loop since it just refers to different file. Try the following code.
UnTested
Sub Conso()
Dim DailyRptTemplate As Workbook, MasterSht As Worksheet, TempWbk As Workbook
' Get common values, eg. path, date
Call getValues
Set DailyRptTemplate = Workbooks("Daily Reporting Template.xlsm")
Set MasterSht = DailyRptTemplate.Worksheets("Master")
Application.DisplayAlerts = False
'Open Staff Input Value
Dim i As Integer
'Dim j As Long
'j = Cells(Rows.Count, 13).End(xlUp).Row
For i = 7 To 30
StaffPath = MasterSht.MasterShtCells(i, 4).Value
WS = MasterSht.Cells(i, 3).Value
THPath = MasterSht.Cells(3, 2).Value
wrkFold = MasterSht.Cells(2, 2).Value
Filename = MasterSht.Cells(4, 2).Value
'Open Template
'Workbooks.Open Filename:= _
'wrkFold & "Master TH\Template\Daily Reporting Template.xlsm", UpdateLinks:=3
Set TempWbk = Workbooks.Open(Filename:=StaffPath & "\" & Filename & ".xlsm", UpdateLinks:=3)
TempWbk.Cells.Copy
DailyRptTemplate.Worksheets(WS).Range("A1").Paste
DailyRptTemplate.SaveAs Filename:=THPath & "Daily Reporting Template" & ".xlsm" _
, FileFormat:=xlOpenXMLWorkbookMacroEnabled, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
TempWbk.Close (False)
Next i
Application.DisplayAlerts = True
End Sub
It is also worth to have look at the below section since these are not looped through the procedure.
THPath = MasterSht.Cells(3, 2).Value
wrkFold = MasterSht.Cells(2, 2).Value
Filename = MasterSht.Cells(4, 2).Value
each day I import some files into a master spreadsheet. The file has a time stamp random 8 digit number generated so I cant anticipate the file name. I previously had ???????? in place of the code which was working. After some IT changes it doesn't work now, we just changed drives and I updated the location all is fine if I add the sequence instead of ???'s
How can I make it so that I can mimic the effect I had before where ?????? worked - most of the file name is unique and can be estimated _ ( with dates etc.) but its just the last 8 digits.
Dim Wb1 As Workbook
Dim Wb2 As Workbook
Dim filepath As String
filepath = Sheets("control").Cells(1, 5).Value
Application.ScreenUpdating = False
Set Wb1 = Workbooks.Open("C:\Users\damian_MCP\Mobius Capital Partners\Mobius _
Capital Partners Team Site - Documents\Operations\FTP\" & filepath & _
"\5446890_FMCM_" & filepath & "_(76765435).xls")
'current acc FMCM
... workaround for the this part
Set Wb1 = Workbooks.Open("C:\Users\damian_MCP\Mobius Capital Partners\Mobius_
Capital Partners Team Site - Documents\Operations\FTP\" & filepath & _
"\5446890_FMCM_" & filepath & "_(76765435).xls")
how can I edit this to search for just FMCM ?
Sub ubstransi()
Application.DisplayAlerts = False
Sheets("ubs trans").Select
' This section could have an unexpected result because it is not clear which cells are you clearing
Cells.Select
Selection.ClearContents
Dim Wb1 As Workbook
Dim Wb2 As Workbook
Dim filepath As String
filepath = Sheets("control").Cells(1, 5).Value
Set Wb1 = Workbooks.Open("C:\Users\damian_MCP\Mobius Capital Partners\Mobius Capital Partners Team Site - Documents\Operations\FTP\" & filepath & "\5446890_FMCM_" & filepath & "_(76882269).xls")
'FMCM *** NOTE that there is no wildcard in your code...
Wb1.Sheets("Cash Movement").Range("A1:x100").Copy
Windows("MEMF RECS2.xlsm").Activate
Sheets("ubs trans").Range("a1").PasteSpecial Paste:=xlPasteAll
Sheets("UBS trans").Select
Range("AD2").Select
ActiveCell.FormulaR1C1 = _
"=IF(AND((IF(OR(RC[-22]=""FOREX TRADE SPOT"",RC[-22]=""Transfer"",LEFT(RC[-22],5)=""UBSFX"",LEFT(RC[-22],6)=""UBS FX""),""FX"",0)=""FX""),RC[-21]=control!R2C3),""FX"",0)"
Range("AD2").Select
Selection.Copy
Range("AD100").Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Wb1.Close SaveChanges:=False
Set Wb2 = Workbooks.Open("C:\Users\damian_MCP\Mobius Capital Partners\Mobius Capital Partners Team Site - Documents\Operations\FTP\" & filepath & "\5446890_FMSH_" & filepath & "_(76885899).xls")
'FMSH *** NOTE that there is no wildcard in your code...
Wb2.Sheets("Securities Holdings").Range("A1:X100").Copy
Windows("MEMF RECS2.xlsm").Activate
Sheets("UBS AM POS").Range("a1").PasteSpecial Paste:=xlPasteAll
Wb2.Close SaveChanges:=False
Windows("MEMF RECS2.xlsm").Activate
Sheets("BBGCASH").Select
Range("A1").Select
Dim datename As String
Dim datename2 As String
datename = Sheets("control").Cells(1, 5).Value
datename2 = Sheets("control").Cells(2, 5).Value
' This instruction can not be handle as it is not setting to any var.
Workbooks.Open Filename:= _
"C:\Users\damian_MCP\Mobius Capital Partners\Mobius Capital Partners Team Site - Documents\Operations\FTP\" & datename & "\f3576cshdump2.ext." & datename2 & ".1.txt"
Columns("A:A").Select
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Cells.Select
Selection.Copy
Windows("MEMF RECS2.xlsm").Activate
Sheets("BBGCASH").Select
Range("A1").Select
ActiveSheet.Paste
Sheets("control").Select
End Sub
Try this one:
Sub Open_Workboook()
Dim WB As Workbook
Dim MyPath As String, MyFile As String
Dim filepath as String
filepath = Sheets("control").Cells(1, 5).Value
MyPath = "C:\Users\damian_MCP\Mobius Capital Partners\Mobius _
Capital Partners Team Site - Documents\Operations\FTP\"
MyFile = Dir(MyPath & "*_FMCM_" & filepath & "_(76765435).xls")
Do While MyFile <> ""
Application.ScreenUpdating = False
Set WB = Workbooks.Open(MyPath & MyFile)
MyName = WB.Name
If MsgBox("Is this the file you want to open?" & vbTab & MyName, vbYesNo) = vbYes Then
GoTo continue
Else
WB.Close
End If
MyFile = Dir()
Loop
Exit Sub
continue:
WB.Close
MsgBox "File Find... and close " & MyName
End Sub
It will work, later just adapt.
Hope it helps
I have complied the below code for creating a separate bank payment sheet, everything is working fine but it is not deleting the rows of the cells whose value is "Delete" in column "E".
i have also observed while debugging that sometimes it deletes and sometimes it don't.
but now it is not deleting at all.
where I'm going wrong?
Sub Create_Bank_Sheet()
Dim fname As String
Dim path As String
Dim varResponse As Variant
Application.DisplayAlerts = False
varResponse = MsgBox("Select 'Yes' or 'No' File will be Saved at : " & Range("c43").Value, vbYesNo, "Are you sure you want to SaveAs this Sheet?")
If varResponse <> vbYes Then Exit Sub
Sheets("Bank Sheet for Payment").Select
path = Sheets("Command Center").Range("c43")
fname = Sheets("Command Center").Range("c42")
ThisWorkbook.Sheets("Bank Sheet for Payment").Copy
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Dim c As Range
Dim SrchRng As Range
Dim SrchStr As String
Set SrchRng = ActiveSheet.Range("e4", ActiveSheet.Range("e65536").End(xlUp))
SrchStr = "Delete"
Do
Set c = SrchRng.Find(SrchStr, LookIn:=xlValues)
If Not c Is Nothing Then c.EntireRow.Delete
Loop While Not c Is Nothing
ActiveWorkbook.Save
MsgBox ("File saved in " & path)
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
You're not setting your SrchRng correctly.
Try
Set SrchRng = ActiveSheet.Range("E4:E" & ActiveSheet.Range("E65536").End(xlUp).Row)
I have a task to add workbook name into all worksheet's first column hence i need to have a macro and below is a draft of the same
Sub InsertWorkbookName()
Path = "C:\Users\mechee69\Download\"
Filename = Dir(Path & "*.xls")
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Columns("A:A").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A1").Select
ActiveCell.SpecialCells(xlLastCell).Select
Application.Goto Range("A" & ActiveCell.Row), True
ActiveCell.Select
ActiveCell.FormulaR1C1 = _
"=RIGHT(LEFT(CELL(""filename""),FIND(""."",CELL(""filename""),FIND(""["",CELL(""filename""),1))-1),FIND(""."",CELL(""filename""),FIND(""["",CELL(""filename""),1))-FIND(""["",CELL(""filename""),1)-1)"
Application.Goto Range("A" & ActiveCell.Row), True
ActiveCell.Select
Selection.Copy
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
ActiveWorkbook.Save
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
Try this
Sub WorkbookName()
Dim wbk As Workbook
Dim strFilename As String
Dim strPath As String
Dim wc As Worksheet
Dim lngLastR As Long
Dim lngSecurity as Long
lngSecurity = Application.AutomationSecurity
Application.AutomationSecurity = msoAutomationSecurityLow
strPath = "[Full Folder Path]"
strFilename = Dir(strPath & "*.xlsx")
Do While strFilename <> ""
Set wbk = Workbooks.Open(strPath & strFilename)
For Each ws In wbk.Worksheets
lngLastR = ws.Range("A" & Rows.Count).End(xlUp).Row
ws.Range("A:A").Insert Shift:=xlToRight
ws.Range("A1:A" & lngLastR).Value = wbk.Name
Next
wbk.Save
wbk.Close False
strFilename = Dir
Loop
Application.AutomationSecurity = lSecurity
MsgBox ("Done")
End Sub
As a quick run through of what this code does.
'Dir' goes through a folder on a criteria, the criteria in this case being ".xlsx" this is to make sure it only opens xlsx files.
'Do While' is a form of loop, this will repeat all code between the "Do While" and the "Loop" until the condition is no longer true.
Once deciding on the file it opens the workbook and remembers it as a variable, this is so I can reference it's name more easily.
I then find the last used row by starting at the bottom cell of row "A" and going up until there is data in a cell. There is a write up on this on stack overflow (Link: Error in finding last used cell in VBA)
I then insert a row to the left pushing the data to the right and set the value of all cells in row 'A' in the used ranged to the name of the workbook using the workbooks '.Name' function.
I then save and close the workbook before using the 'Dir' to the next file name ready to start the process again, this will repeat for all files and give you a message box saying "Done" once it has completed them all.
If you have any questions let me know
Edited to include a bypass for protected view
So this Macro will open Excel Files in a Folder with a specific format, then it prints the workbookname in A1 in every sheet of that file. It ignores the master, if its in the same folder.
Sub WorkbookName()
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Dim lastRow As Long
Dim lSecurity As Long
On Error Resume Next
Path = "C:\Users\User\Desktop\Files\" 'Folder of your Files
Filename = Dir(Path & "*.xlsx") 'Format of your files
Do While Filename <> "" And Filename <> "Master.xlsm" 'Dont Open MasterFile
Set wbk = Workbooks.Open(Path & Filename)
lSecurity = Application.AutomationSecurity
Application.AutomationSecurity = msoAutomationSecurityLow
For Each ws In wbk.Worksheets
With ws
.Range("A1").EntireColumn.Insert
lastRow = .Cells(Rows.Count, 2).End(xlUp).Row
.Range(Cells(1, 1), Cells(lastRow, 1)).Value = ActiveWorkbook.Name
End With
Application.AutomationSecurity = lSecurity
Next ws
wbk.Close True
Filename = Dir
Loop
End Sub