Excel Macro to Concatenate first and last name sometimes fails - excel

I am a Visual Basic newbie. From hints on the web, I pieced together an Excel macro that does several things, including concatenating first and last name, in a loop, to make a new column with those joined. Half the time it works great, half the time I end up with no space between the first and last name. (In those cases, closing, re-opening, and re-running almost always works.) Is this a timing issue? I'll put in the whole macro but it's the Do While loop near the top that I think is the problem.
Thanks for any help.
Sub WholeThing()
'
' WholeThing Macro
Application.ScreenUpdating = False
ActiveSheet.Name = "original"
Rows("1:1").Delete Shift:=xlUp
Do While ActiveCell <> "" 'Loops until the active cell is blank.
ActiveCell.Offset(0, 0).FormulaR1C1 = _
ActiveCell.Offset(0, 1) & " " & ActiveCell.Offset(0, 2)
ActiveCell.Offset(1, 0).Select
Loop
Application.Wait (Now + TimeValue("0:00:02"))
Sheets.Add After:=Sheets(Sheets.Count)
Sheets.Add After:=Sheets(Sheets.Count)
Sheets.Add After:=Sheets(Sheets.Count)
Sheets.Add After:=Sheets(Sheets.Count)
Sheets.Add After:=Sheets(Sheets.Count)
Sheets.Add After:=Sheets(Sheets.Count)
Sheets("Original").Activate
ActiveWindow.WindowState = xlNormal
Application.CutCopyMode = False
Application.DisplayAlerts = False
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ActiveSheet.Paste Destination:=Worksheets("Sheet6").Range("A1")
Range("D1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ActiveSheet.Paste Destination:=Worksheets("Sheet6").Range("B1")
Sheets("Original").Activate
ActiveWindow.WindowState = xlNormal
Application.CutCopyMode = False
Application.DisplayAlerts = True
Columns("Y:Y").Copy
ActiveSheet.Paste Destination:=Worksheets("Sheet2").Range("A1")
Columns("Z:Z").Copy
ActiveSheet.Paste Destination:=Worksheets("Sheet3").Range("A1")
Columns("AA:AA").Copy
ActiveSheet.Paste Destination:=Worksheets("Sheet4").Range("A1")
Columns("AB:AB").Copy
ActiveSheet.Paste Destination:=Worksheets("Sheet5").Range("A1")
Application.DisplayAlerts = False
Sheets("Sheet5").Activate
ActiveWorkbook.SaveAs Filename:="Y:\Addrs_DL", FileFormat:=xlCSV, _
CreateBackup:=False
Sheets("Sheet4").Activate
ActiveWorkbook.SaveAs Filename:="Y:\Addrs_D", FileFormat:=xlCSV, _
CreateBackup:=False
Sheets("Sheet3").Activate
ActiveWorkbook.SaveAs Filename:="Y:\Addrs_SL", FileFormat:=xlCSV, _
CreateBackup:=False
Sheets("Sheet2").Activate
ActiveWorkbook.SaveAs Filename:="Y:\Addrs_S", FileFormat:=xlCSV, _
CreateBackup:=False
Sheets("Sheet6").Activate
ChDir "Y:\"
Application.ScreenUpdating = True
ActiveWorkbook.SaveAs Filename:="Y:\NAME-ADR.CSV", FileFormat:=xlCSV, _
CreateBackup:=False
' Application.Quit
' Application.ActiveWindow.Close SaveChanges:=False
' ActiveWorkbook.Close SaveChanges:=False
End Sub

By not using ActiveCell and working with your range directly, you can make your code more stable and more reliable.
Consider something like this (see notes about assumptions on range and cell references).
Dim ws as Worksheet
Set ws = ThisWorkbook.Sheets("original")
With ws
Dim lRow as Long
lRow = .Range("B" & .Rows.Count).End(xlup).Row 'assumes first name in column B
'assumes concatenated name goes in column A, starting at row 1 (and the first and last name are in B and C, respectively
.Range("A1:A" & lRow).FormulaR1C1 = "=RC[1] & "" "" & RC[2]"
'if you want to copy as values you can use this
.Range("A1:A" & lRow).Value = .Range("A1:A" & lRow).Value
End With
You can also work with the same principles of working directly with the object later on in your code, like this:
'lRow would be the last row of data in the column (assumes same row for each column, based on dataset)
ws.Range("Y1:Y" & lRow).Copy Worksheets("Sheet2").Range("A1")
Doing this will save a lot of processing time as copying entire columns is very inefficient if it's not truly needed.

To do the concatenate, I had first to use this to get the number of the last row:
Dim LastRow As Long
With ActiveSheet
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
That enabled this loop to do the concatenation:
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("original")
With ws
For i = 1 To LastRow
Cells(i, 1) = Cells(i, 2) & " " & Cells(i, 3)
Next i
Then, for the second block (the "With ws" being still in effect):
Sheets("Original").Activate
Range("Y1:Y" & LastRow).Copy Worksheets("Sheet2").Range("A1")

Related

Activesheet shifting away from original sheet on second iteration of the substatement

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

Macro saved as CSV stops Macro from working

I'm working on a Macro that makes several CSV files from a certain area while applying a filter. There are two issues.
The workbook will be saved as a file-format retrieved from it's name (cell B15 and the word 'Week')
I cannot find a way to loop this Macro until Cell B15 is empty.
Can anyone help? Thanks in advance.
Example wrong format:
Sub CSVMaker()
'
' CSVMaker Macro
'
'
ActiveSheet.Range("$A$17:$M$240000").AutoFilter Field:=2, Criteria1:="<>"
Range("A18:B18").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets.Add.Name = Range("A10").Value & "." & Range("A7").Value & "." & "Week" & Range("B15").Value
ActiveSheet.Paste
Application.CutCopyMode = False
Application.DisplayAlerts = False
ActiveSheet.Copy
ActiveWorkbook.SaveAs Filename:=ActiveSheet.Name, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
Sheets("Input").Select
Columns("B:B").Select
Range("B6").Activate
Selection.Delete Shift:=xlToLeft
End Sub
So finally the answer is the filename needs a correct extension like Filename:=ActiveSheet.Name & ".csv".
And I recommend to avoid .Select and do the following:
Option Explicit
Public Sub CSVMaker()
Dim ws As Worksheet
Set ws = ActiveSheet 'better ThisWorkbook.Worksheets("your-sheet-name")
ws.Range("$A$17:$M$240000").AutoFilter Field:=2, Criteria1:="<>"
ws.Range("A18:B18", ws.Range("A18:B18").End(xlDown).End(xlDown)).Copy
Dim SheetName As String
SheetName = ws.Range("A10").Value & "." & Range("A7").Value & "." & "Week" & Range("B15").Value
ThisWorkbook.Sheets.Add.Name = SheetName
ThisWorkbook.Sheets(SheetName).Paste
Application.CutCopyMode = False
Application.DisplayAlerts = False
ThisWorkbook.Sheets(SheetName).Copy
ActiveWorkbook.SaveAs Filename:=SheetName & ".csv", FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
ThisWorkbook.Sheets("Input").Columns("B:B").Delete Shift:=xlToLeft
End Sub

VBA copy paste codes does not pasting anything

Can someone please let me know why my code is not pasting anything from my source data to my destination file?
The objectives of this code are to select rows that satisfy certain criteria, copy-pastes it into another workbook, The code is shown below:
Sub Copy_Source_LRE()
Dim LastRow As Integer, i As Integer, erow As Integer
Workbooks.Open _
"C:\Users\sjiang\OneDrive - Canada Pension Plan Investment Board\Desktop\IOA Exposure\AAPAF_strategy_loadings_2019-04-01_2020-04-01 (2).csv"
Worksheets("AAPAF_strategy_loadings_2019-04").Activate
Set sht = ActiveSheet
'Workbooks("AAPAF_strategy_loadings_2019-04-01_2020-04-01 (2).csv").Sheets("AAPAF_strategy_loadings_2019-04").Activate
LastRow = sht.Cells(sht.Rows.Count, "B").End(xlUp).Row
For i = 2 To LastRow
For Each d In Array("4/1/2019", "5/1/2019", "6/3/2019", "7/1/2019", "8/1/2019", "9/2/2019", _
"10/1/2019", "11/1/2019", "12/2/2019", "1/2/2020", "2/3/2020", "3/2/2020")
If Cells(i, 2) = d And Cells(i, 3) = "Real Estate" And Cells(i, 4) = "Listed Real Estate" And Cells(i, 5) = "AAPAF_SA" Then
Range(Cells(i, 2), Cells(i, 12)).Select
Selection.Copy
Workbooks.Open _
"C:\Users\sjiang\OneDrive - Canada Pension Plan Investment Board\Desktop\IOA Exposure\pull data.xlsm"
Worksheets("Sheet1").Select
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Cells(erow, 1).Select
ActiveSheet.Paste
ActiveWorkbook.Save
'ActiveWorkbook.Close
End If
Next d
Next i
Application.CutCopyMode = False
End Sub
This is a really easy and basic way that I use all the time to copy data into new workbooks. In this example I'm copying a named range called "MasterData" into a new blank workbook. Then I save that new book with a password and re-activate the current workbook.
Dim newfilename As String
newfilename = "/Users/" & userName & "/Desktop/savedWorkbook.xlsx"
Dim NewBook As Workbook
Set NewBook = Workbooks.Add
ThisWorkbook.Activate
Sheets("Datasheet").Select
Range("MasterData").Copy
NewBook.Activate
NewBook.Sheets(1).Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
NewBook.SaveAs Filename:=newfilename, Password:="examplepassword", AccessMode:=xlExclusive, ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
NewBook.Close (True)
ThisWorkbook.Activate
I've redone the code for you as the major problem was related to a loop that is not really necessary. The best/fast way to apply those criteria and extract the data is using a filter to apply them, so copy the visible cells without the hidden (unmatching) lines and then open the second file where you need to past info, find next blank line below selection and paste all lines at once.
I'm pasting the code below (with comments) and also saved a zip file with 3 files (code, info, database) that might reflect your working files, link below.
VBS code:
Sub Copy_Source_LRE()
Dim LastRow As Integer, i As Integer, erow As Integer
Workbooks.Open ThisWorkbook.Path & "\" & "Wks1.xlsx" 'change the path and name here
Worksheets(1).Activate
Set sht = ActiveSheet
LastRow = Range("a1").SpecialCells(xlCellTypeLastCell).Row
datar = Range(Cells(LastRow, 12), Cells(1, 1)).Address 'data range
Range(datar).Select
Selection.AutoFilter 'create a filter,then use the criteria you need
ActiveSheet.Range(datar).AutoFilter Field:=2, Criteria1:= _
Array("4/1/2019", "5/1/2019", "6/3/2019", "7/1/2019", "8/1/2019", "9/2/2019", _
"10/1/2019", "11/1/2019", "12/2/2019", "1/2/2020", "2/3/2020", "3/2/2020"), Operator:=xlFilterValues 'your dates array can be update here
ActiveSheet.Range(datar).AutoFilter Field:=3, Criteria1:="Real Estate", Operator:=xlAnd
ActiveSheet.Range(datar).AutoFilter Field:=4, Criteria1:="Listed Real Estate", Operator:=xlAnd
ActiveSheet.Range(datar).AutoFilter Field:=5, Criteria1:="AAPAF_SA", Operator:=xlAnd
Range(datar).Offset(1, 0).Resize(Range(datar).Rows.Count - 1, Range(datar).Columns.Count).Select 'resize selection to remove the header
Selection.SpecialCells(xlCellTypeVisible).Select 'select visible cells only
Selection.Copy
Workbooks.Open ThisWorkbook.Path & "\" & "Wks2.xlsx" 'change the path and name here
Worksheets("Sheet1").Select
Range("A1").End(xlDown).Offset(1, 0).Select 'goes to the last row on column A the goes another one - 1st empty
ActiveSheet.Paste
ActiveWorkbook.Save
ActiveWorkbook.Close SaveChanges:=True 'close and save your database
Application.CutCopyMode = False
ActiveWorkbook.Close SaveChanges:=False 'close without saving your csv file
End Sub
link to files/code: https://drive.google.com/file/d/1zL_TwclHR4lrNhKB1xODGAmliPHM1r3K/view?usp=sharing
If the solution matches you need please consider as solution. Regards!

Loop through some files (open, add a column, save, and close)

I want to open a file (not all the files in a folder), add a column, save the change, and then close. I want to iterate through some files and do the same things.
I saved my file with names including date (yyyymmdd) such as output_20181112_samples.csv
Let's say I want to iterate through two files, output_20181113_samples.csv & output_20181114_samples.csv
I thought I could use I (iteration index) and put it in the middle of the file name but it didn't work out. I tried to find a solution but most of the answers are for iterating through all the files in a folder.
Sub open_add_col_save_close()
Dim i As Interger
For i = 1 To 10
Select Case i
Case 3, 4
Workbooks.Open Filename:="C:\Users\todd\Downloads\output_2018111" & i & "_samples.csv"
Columns("B:B").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
ActiveCell.FormulaR1C1 = "2018111" & i
ActiveCell.Offset(0, 0).Select
Selection.Copy
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.End(xlUp).Select
ActiveCell.FormulaR1C1 = "date"
Range("B2").Select
Workbooks("output_2018111" & i & "_samples.csv").Save
SendKeys "%s~"
Workbooks("output_2018111" & i & "_samples.csv").Close
End Select
Next i
End Sub
Try,
Sub open_add_col_save_close()
Dim Fn As String
Dim Wb As Workbook
Dim Ws As Worksheet
Dim i As Integer
For i = 1 To 10
Fn = "C:\Users\todd\Downloads\output_2018111" & i & "_samples.csv"
Select Case i
Case 3, 4
Set Wb = Workbooks.Open(Filename:=Fn, Format:=2)
Set Ws = Wb.ActiveSheet
With Ws
.Columns("B:B").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
.Range("A1").End(xlDown).Offset(0, 1) = "2018111" & i
.Range("b1", .Range("b1").End(xlDown)) = "2018111" & i
.Range("b1") = "date"
End With
Wb.Save
Wb.Close (0)
End Select
Next i
End Sub

How to enter data from a form on one sheet onto a log on another sheet

So I'm trying to figure out how I can setup a macro that will take the data that I enter into a form on one sheet then log it into a log in another sheet. It will log it but my big problem is that it needs to go to the next line and I can't quite figure out the code for it. Here is what my code looks like:
Sub Appt()
'
' Appt Macro
'
'
Range("E4").Select
Selection.Copy
Sheets("Appointments").Select
Range("G7").Select
ActiveSheet.Paste
Sheets("Data Entry").Select
Range("E6").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Appointments").Select
Range("D7").Select
ActiveSheet.Paste
Sheets("Data Entry").Select
Range("E8").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Appointments").Select
Range("E7").Select
ActiveSheet.Paste
Sheets("Data Entry").Select
Range("E10").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Appointments").Select
Range("F7").Select
ActiveSheet.Paste
Sheets("Data Entry").Select
Range("E12").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Appointments").Select
Range("H7").Select
ActiveSheet.Paste
Sheets("Data Entry").Select
Range("E4").Select
Application.CutCopyMode = False
Selection.ClearContents
Range("E6").Select
Selection.ClearContents
Range("E8").Select
Selection.ClearContents
Range("E10").Select
Selection.ClearContents
Range("E12").Select
Selection.ClearContents
End Sub
To get the next empty row on Sheets("Appointments") you would use this formula to get the row number:
tRw = Sheets("Appointments").Range("D" & Rows.count).End(xlUp).Offset(1).Row
This assumes that there is nothing in column D below what you are pasting.
It is apparent that you used the macro recorder, and this is a great way to learn. But using the .select so much will slow things down and is unneeded.
To get around that declare the sheets as variables and then one line for each copy paste is needed.
Sub APPT()
Dim oWs As Worksheet
Dim tWs As Worksheet
Dim tRw As Long
Set oWs = Sheets("Data Entry")
Set tWs = Sheets("Appointments")
tRw = tWs.Range("D" & Rows.count).End(xlUp).Offset(1).Row
With oWs
.Range("E4").copy tWs.Range("G" & tRw)
.Range("E6").copy tWs.Range("D" & tRw)
.Range("E8").copy tWs.Range("E" & tRw)
.Range("E10").copy tWs.Range("F" & tRw)
.Range("E12").copy tWs.Range("H" & tRw)
.Range("E4").ClearContents
.Range("E6").ClearContents
.Range("E8").ClearContents
.Range("E10").ClearContents
.Range("E12").ClearContents
End With
End Sub
For other methods of finding the next row look at Siddharth Rout's answer here.
And as BruceWayne stated in his comment, this is a great reference as to why/how to avoid using .select
It's best to avoid the user's clipboard and to assign the values directly:
Sub Appt()
Dim n&, v
v = [transpose(offset('data entry'!e4,{0;2;4;6;8},))]
With Sheets("appointments")
n = .Range("d" & .Rows.Count).End(xlUp).Row
.[g1].Offset(n) = v(1)
.[d1].Offset(n) = v(2)
.[e1].Offset(n) = v(3)
.[f1].Offset(n) = v(4)
.[h1].Offset(n) = v(5)
End With
Sheets("data entry").Range("e4,e6,e8,e10,e12").ClearContents
End Sub

Resources