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
Related
I can run this program one iteration at a time, but when I let it run on the next i, the VarCellValues come back as values from a different sheet. What would be causing the active sheet to change away from the workbook and first sheet the macro is opened from?
Sub copy_financials_2022()
'
' copy_financials_2022 Macro
'
Dim i As Integer
Dim VarCellValue As String
Dim VarCellValue2 As String
Dim VarCellValue3 As String
Dim VarCellValue4 As String
Dim VarCellValue5 As String
Dim currwbk As Workbook
Set currwbk = ThisWorkbook
For i = Range("A2").Value To Range("C2").Value
Set currwbk = ThisWorkbook
VarCellValue = Range("B" & i).Value
VarCellValue2 = Range("C" & i).Value
VarCellValue3 = Range("A" & i).Value
VarCellValue4 = Range("D" & i).Value
VarCellValue5 = Range("E" & i).Value
Application.DisplayAlerts = False
Workbooks.Open (Range("A3").Value & VarCellValue4 & ".xlsx")
'Workbooks.Open ("S:\Finance\_2022 FINANCIAL REPORTS\National Financials\09-30\CONSOLIDATED MONTHLY FINANCIAL STATEMENT" & ".xlsm")
'Workbooks.Open (Range("B3").Value & VarCellValue4)
Workbooks(VarCellValue4).Activate
'inserted "Sheets(VarCellValue5).Activate" below after the third tab was active on Los Angeles Sheet (should have been the first tab)
Sheets(VarCellValue5).Activate
Sheets(VarCellValue5).Unprotect Password:="forecast22"
Columns("A:S").Select
Selection.EntireColumn.Hidden = False
Workbooks.Open ("S:\Finance\_2022 FINANCIAL REPORTS\National Financials\09-30\CONSOLIDATED MONTHLY FINANCIAL STATEMENT" & ".xlsm")
Sheets(VarCellValue2).Activate
Range("A6:Q6").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range("A6:Q88").Select
Selection.Copy
Workbooks(VarCellValue4).Activate
Range("A6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("B:B,D:E,G:G,I:J,L:N,K:K").Select
Range("K1").Activate
Selection.EntireColumn.Hidden = True
Range("C7").Select
'Range("A6").Select
Application.CutCopyMode = False
ActiveWorkbook.Save
Range("C7").Select
ActiveCell.FormulaR1C1 = "Sept MTD"
Range("H7").Select
ActiveCell.FormulaR1C1 = "Sept YTD"
Range("S8").Select
ActiveCell.FormulaR1C1 = "Aug - Dec 2021"
Range("A6").Select
ActiveSheet.Protect Password:="forecast22"
ActiveWorkbook.Save
ActiveWindow.Close
'Workbooks.Close ("S:\Finance\_2022 FINANCIAL REPORTS\National Financials\05-31\CONSOLIDATED MONTHLY FINANCIAL STATEMENT" & ".xlsm")
Next i
End Sub
Instead of relying on a sheet being active, fully qualify each Range call with the appropriate workbook/worksheet.
Dim currwbk As Workbook
Set currwbk = ThisWorkbook
Dim currWs As Worksheet
Set currWs = currwbk.ActiveSheet
For i = currWs.Range("A2").Value To currWs.Range("C2").Value
VarCellValue = currWs.Range("B" & i).Value
VarCellValue2 = currWs.Range("C" & i).Value
VarCellValue3 = currWs.Range("A" & i).Value
VarCellValue4 = currWs.Range("D" & i).Value
VarCellValue5 = currWs.Range("E" & i).Value
Dim wb As Workbook
Set wb = Workbooks.Open(currWs.Range("A3").Value & VarCellValue4 & ".xlsx")
With wb.Worksheets(VarCellValue5)
.Unprotect Password:="forecast22"
.Columns("A:S").Hidden = False
' and so on
End With
Next
Could someone sell me why I am getting a runtime error here?? I have almost this identical code in another project that works, and I cant figure out the issue.
Sub Create_PDF()
' Create and save .pdf
Dim pdfName As String
Dim myrange As String
myrange = Cells(Rows.Count, 6).End(xlUp).Address
Dim AccountNumber As String
AccountNumber = Right(A1, 3)
FullName = "P:\Public\Generated Letters\LTXN Export Spreadsheets\" & "AccountEnding" & AccountNumber & ".pdf"
'Sets the name and location for the new file
myrange = Cells(Rows.Count, 6).End(xlUp).Address
'sets the string end for the print area
With ActiveSheet.PageSetup
.PrintArea = "A1:" & myrange
.Orientation = xlLandscape
.Zoom = False
.FitToPagesTall = False
.FitToPagesWide = 1
End With
'Setting the spreadsheet to print active content with columns fit to single page
If Dir(FullName) <> vbNullString Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="P:\Public\Generated_Letters\LTXN_Export_Spreadsheets\" & "AccountEnding" & AccountNumber & " - " & Format(Now, "mm.dd.yyyy hh mm") & ".pdf" _
, Quality:=xlQualityMedium, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
Else
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="P:\Public\Generated_Letters\LTXN_Export_Spreadsheets\" & "AccountEnding" & AccountNumber & Format(Now, "mm.dd.yyyy hh mm") & ".pdf" _
, Quality:=xlQualityMedium, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
'###This is where I am getting the runtime error and the file is not saving###
End Sub
Sub openFolder()
'Open the folder that we save the PDF to
Call Shell("explorer.exe" & " " & "P:\Public\Generated Letters\LTXN Export Spreadsheets\", vbNormalFocus)
End Sub
The one difference from the other project is that AccountNumber is a number and not text, but I figured in defining it as a string it shouldnt matter???
Try this:
Option Explicit
'use Const for fixed values
Const EXPORTS As String = "P:\Public\Generated Letters\LTXN Export Spreadsheets\"
Sub Create_PDF()
Dim ws As Worksheet, myRange As Range
Dim AccountNumber As String, dt As String, FullName As String, fName As String, sep As String
Set ws = ActiveSheet
AccountNumber = Right(ws.Range("A1").Value, 3) 'not just `A1`
With ActiveSheet.PageSetup
.PrintArea = "A1:" & ws.Cells(Rows.Count, 6).End(xlUp).Address
.Orientation = xlLandscape
.Zoom = False
.FitToPagesTall = False
.FitToPagesWide = 1
End With
dt = Format(Now, "mm.dd.yyyy hh mm")
fName = EXPORTS & "AccountEnding" & AccountNumber
If Len(Dir(fName & ".pdf")) > 0 Then sep = " - "
fName = fName & sep & dt & ".pdf"
'note there's no `xlQualityMedium` enumeration for `Quality`
ws.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fName, _
Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
Sub openFolder()
'Folder paths with spaces need to be quoted....
Call Shell("explorer.exe" & " """ & EXPORTS & """", vbNormalFocus)
End Sub
I have an excel macro that can separate and save files per column. My problem is this, the cells from the column I want to be separated cannot be saved as ".xls" if cell has dot "." in the text.
For example: DEF. corp
File when downloaded in my computer
What should I change in my VBA code below to make it work?
Dim MyFile, NewFile As Variant
Dim sort_data As String
Dim last_row, tfiles, start_row, ktr As Long
'Sort data
Range(Separate.left_column & Separate.last, Separate.right & last_row).Select
Selection.sort Key1:=Range(Separate.sort & Separate.last + 1), Order1:=xlAscending, Header:=True, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
'Initiate variable
tfiles = 0
'Loop through data
start_row = Separate.last + 1
For ktr = Separate.last + 1 To last_row
'Identify data
sort_data = Trim(UCase(Range(Separate.sort & start_row).Value))
'End of same data
If sort_data <> Trim(UCase(Range(Separate.sort & ktr).Value)) Then
'Copy and paste header
Range(Separate.left_column & Separate.first, Separate.right & Separate.last).Copy
Workbooks.Add
ActiveSheet.Paste
NewFile = ActiveWorkbook.Name
Windows(MyFile & "xlsx").Activate
'Copy and paste data
Range(Separate.left_column & start_row, Separate.right & ktr - 1).Copy
Windows(NewFile).Activate
Range(Separate.left_column & Separate.last + 1).Select
ActiveSheet.Paste
'Bold header rows
Rows(Separate.first).Select
Selection.Font.Bold = True
Range(Separate.left_column & last + 1).Select
'Auto fit
Cells.Select
Cells.EntireColumn.AutoFit
Cells.EntireRow.AutoFit
'Save workbook
Range(Separate.left_column & Separate.last + 1).Select
new_file = IIf(Separate.current_file = True, MyFile & _
" ", "") & IIf(Len(Trim(Separate.prefix)) > 0, _
Separate.prefix & " ", "") & sort_data & _
IIf(Len(Trim(Separate.suffix)) > 0, _
" " & Separate.suffix, "") '& "xlsx"
ActiveWorkbook.SaveAs Filename:=new_file, FileFormat:= _
xlNormal, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
'Close workbook and return to original
ActiveWorkbook.Close
tfiles = tfiles + 1
start_row = ktr
Use a replace to modify your string variable new_file to be an underscore _ or something. Underscore is one of the better choices in that it allows for double click full selection of a file name (vs using a dash) and is usually accepted by websites and other file hosting systems.
Just add the below line before your ActiveWorkbook.SaveAs procedure.
new_file = replace(new_file,".","_")
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
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