Copy and paste a row into column using macro - excel

I am very new to the macro..
Basically I wanted to copy a row (E23 to H23) from worksheet named "Present month" of one workbook to a column of another worksheet named "ANA" (K4 to K7) in another workbook.
Please help me out!!
Edit1: Code from comment
Sub Copy_and_update_last_col_Census()
Range("K4:K7").Select
Selection.ClearContents
Application.WindowState = xlNormal
'the below line throws error
Windows("NOL_Support_Ticket_Status_Report").Activate
Range("E25:H25").Select
Selection.copy
Windows("Charts.xlsm").Activate
Range("K9").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.copy
Range("K4").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Application.CutCopyMode = False
Range("K9:N9").Select
Selection.ClearContents
End Sub

This is a tip. Go to the Developers tab -> Record Macro -> do the actions you want -> stop recording and woila press alt + F11 and check out the module.
F8 is your friend and you can see what your recorded macro does!!!

try this:
Sub Copy_and_update_last_col_Census()
Dim wb As Workbook
Dim rng2copy As Range, rng2paste As Range
Dim query As Integer
Dim myfile
Dim filename As String
'~~> I assumed that Charts.xlsm is the workbook you are running the macro
Set rng2paste = ThisWorkbook.Sheets("ANA").Range("K4")
filename = "NOL_Support_Ticket_Status_Report.xlsx"
'~~> Handles the error if workbook is not open
On Error Resume Next
Set wb = Workbooks(filename)
'~~> check for error and execute action necessary
If Err.Number <> 0 Then
query = MsgBox("Source workbook not open." & vbNewLine & _
"Do you want to open it?", vbYesNo)
Else
GoTo proceedcopy
End If
If query = 6 Then
myfile = Application.GetOpenFilename(Filefilter:="Excel Files (*.xlsx), *.xlsx")
Else
MsgBox "Exiting now."
Exit Sub
End If
'~~> check if user selected the correct file
If myfile <> False Then
If Dir(myfile) = filename Then
Set wb = Workbooks.Open(myfile)
Else
MsgBox "Wrong file loaded." & vbNewLine & _
"Exiting now."
Exit Sub
End If
Else
MsgBox "No file loaded." & vbNewLine & _
"Exiting now."
Exit Sub
End If
'~~> this do the actual copying
proceedcopy:
Set rng2copy = wb.Sheets("Present Month").Range("E23", "H23")
rng2copy.Copy
rng2paste.PasteSpecial xlPasteValues, , , True
Application.CutCopyMode = False
wb.Close False
End Sub
This is tried and tested.
But i can't say that i've structured it well enough.
So i leave further testing to you.

Related

Excel file import, Comma as delimiter

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 code is not deleting rows, rest all is working fine

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)

Macro for Row killer + Convert all fields as zero + Save as .xls

I need help in achieving the below in my excel sheet with one master MACRO VBA Code
If column A contains 0 - Delete the entire row. ( Row Killer ) - This should run on all the sheets in the workbook
Since the excel file is heavily linked - All fields needs to converted to values (E.g. Paste as Values)
Save AS file in .xls format with the file name SAMAmonthlyReport
I have the code for point 2 and 3 from this site but need help in adding the 1 point.
Below is the code
Sub CopyValuesToSync()
Dim OrigWkbkFpth As String
Dim OrigWkbk As String
Dim ValueWkbk As String
Dim WS As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
OrigWkbkFpth = Application.ActiveWorkbook.FullName
OrigWkbk = Application.ActiveWorkbook.Name
For Each WS In ActiveWorkbook.Worksheets
WS.Select
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Range("A1").Select
Next WS
ActiveWorkbook.SaveAs Filename:="C:\SAMA\SamaMonthly.xls", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
ValueWkbk = Application.ActiveWorkbook.Name
Workbooks.Open Filename:=OrigWkbkFpth
Windows(ValueWkbk).Activate
ActiveWindow.Close
Windows(OrigWkbk).Activate
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
You can add a validation for each cell in column A using something like If cells(oRow,1).Value = 0 Then and then you can delete the Row with
Rows(oRow).EntireRow.Delete

call Sub not working properly

Why this call of sub is not working properly?
I get an error that there are undefined objects.
I believe this can be a little problem but cannot find a solution.
I am trying to make new sheetnames but the code is too long for VBA , so I have to split the code, and continue in a second Sub. (apparently it is limited to 15 of 16 handlings)
Thanks in advance.
below my startcode
Sub Macro1()
' Macro1 Macro
Dim wbNew As Workbook
'sheet 1----------------------------------------------------------------
Application.ScreenUpdating = False
ThisWorkbook.Sheets(1).Activate
Range("A1:S53").Select
Range("S53").Activate
Selection.Copy
Set wbNew = Workbooks.Add
wbNew.Sheets(1).Activate
Range("A1:S53").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
wbNew.Sheets(1).Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range("A1").Select
ActiveSheet.Paste
Range("A15").Select
Call vanaf_17
ActiveWorkbook.SaveAs Filename:= _
"C:\Path\" & "per 1-15" & " " & Format(Range("C13"), "mmmm") & " " & Format(Range("C13"), "YYYY") & ".xlsx"
FileFormat = xlOpenXMLWorkbook
ActiveWindow.Close
End Sub
code to call
Sub vanaf_17()
Dim wbNew As Workbook
Application.ScreenUpdating = False
'sheet 17----------------------------------------------------------------
'here starts a new sheet!!!!!!!!!!!!!
Sheets.Add After:=ActiveSheet
ThisWorkbook.Sheets(1).Activate
Range("A1:S53").Select
Range("S53").Activate
Selection.Copy
'change here sheet nr!!!!!!!
wbNew.Sheets(17).Activate
Range("A1:S53").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
'change here sheet nr!!!!!!!
wbNew.Sheets(17).Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range("A1").Select
ActiveSheet.Paste
'Here ends a new sheet!!!!!
End Sub
You'll need to set wbnew in that second sub as well. The second sub has no idea what you mean when you say wbnew. When you have a variable in a subroutine or function it exists only in the subroutine or function. As soon as you move to another subroutine, your variables are 100% worthless.
To get around this, you can pass parameters between subs.
When you start your second sub Sub vanaf_17() Do it like so:
Sub vanaf_17(wbNew as Workbook)
....your code
End Sub
When you call vanaf_17() do it like so:
Call vanaf_17 webNew
Also, since you are declaring webNew as a workbook in the parameters, delete the dim wbNew as Workbook bit in vanaf_17 otherwise you'll get an error.
Lastly, There is no reason why you need to split these up into two subroutines. I've never heard of '15 or 16 handling' limit and I'm not real sure what that means. I've seen some ugly ass recorded macro code that goes on for thousands of lines of .select and .activate and oh-my-god-no-that-is-such-a-bad-idea for what feels like forever. Excel can handle it.
Updated: Here is what the code would look like with this change:
Sub Macro1()
' Macro1 Macro
Dim wbNew As Workbook
'sheet 1----------------------------------------------------------------
Application.ScreenUpdating = False
ThisWorkbook.Sheets(1).Activate
Range("A1:S53").Select
Range("S53").Activate
Selection.Copy
Set wbNew = Workbooks.Add
wbNew.Sheets(1).Activate
Range("A1:S53").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
wbNew.Sheets(1).Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range("A1").Select
ActiveSheet.Paste
Range("A15").Select
Call vanaf_17 wbNew
ActiveWorkbook.SaveAs Filename:= _
"C:\Path\" & "per 1-15" & " " & Format(Range("C13"), "mmmm") & " " & Format(Range("C13"), "YYYY") & ".xlsx"
FileFormat = xlOpenXMLWorkbook
ActiveWindow.Close
End Sub
Sub vanaf_17(wbNew AS Workbook)
Application.ScreenUpdating = False
'sheet 17----------------------------------------------------------------
'here starts a new sheet!!!!!!!!!!!!!
Sheets.Add After:=ActiveSheet
ThisWorkbook.Sheets(1).Activate
Range("A1:S53").Select
Range("S53").Activate
Selection.Copy
'change here sheet nr!!!!!!!
wbNew.Sheets(17).Activate
Range("A1:S53").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
'change here sheet nr!!!!!!!
wbNew.Sheets(17).Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range("A1").Select
ActiveSheet.Paste
'Here ends a new sheet!!!!!
End Sub
That being said, there are some changes here that I think will help. Namely, you could loop through all the sheets that you care about in thisWorkbook, and call your subroutine to copy and paste the A1:S53 range into a new worksheet in the new workbook. Below I have a quick example of what that would look like. I kept some of the unnecessary .select and .activate stuff in there, because I figured this change was dramatic enough. You'll see that all of your sheet creation and copying/pasting is now done in the second subroutine. The first subroutine just sets up the new workbook, loops through the sheets, and then saves the new workbook.
Sub Macro1()
' Create a new workbook. Then loop through each worksheet in this workbook (that we care about)
' and call the CreateNewWS subroutine to copy the A1:S53 range for each worksheet into the
' new workbook
Application.ScreenUpdating = False
'Create a new workbook, assign it to wbNew variable
Dim wbNew As Workbook
Set wbNew = Workbooks.Add
'Loop through all the sheets in the current workbook that we care about
Dim sheetname as string
For each sheetname in Array("sheet1", "sheet2", "sheet3", "sheet4")
'call the CreateNewWS subroutine to do the sheet creation and copying and pasting
call CreateNewWS wbNew, thisWorkbook.Sheets(sheetname)
Next sheetname
'You could also loop through all of the worksheets in thisworkbook if you want to copy every worksheet:
'Dim ws as worksheet
'For each ws in ThisWorkbook.Worksheets
' call CreateNewWS wbNew, ws
'Next ws
'Save the new workbook
newWb.SaveAs Filename:= _
"C:\Path\" & "per 1-15" & " " & Format(Range("C13"), "mmmm") & " " & Format(Range("C13"), "YYYY") & ".xlsx"
FileFormat = xlOpenXMLWorkbook
'Close the new workbook
newWb.Close
'Don't forget to turn this back on. Yikes.
Application.ScreenUpdating = True
End Sub
Sub CreateNewWS(wbNew AS Workbook, ws as Worksheet)
'This subroutine takes in the wbNew and the worksheet (ws) that we are copying from.
' it copys range A1:S53 from the ws to the wbNew's new worksheet.
'This will hold the new worksheet we are adding to the wbNew
Dim wsNew as worksheet
'Add a new worksheet to the new workbook
wbNew.Activate
set wsNew = wbNew.Sheets.Add After:=ActiveSheet
'Activate and copy from current workbook
ws.Activate
ws.Range("A1:S53").Select
Selection.Copy
'Activate and paste into newWb
wsNew.Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End Sub
I haven't really tested this change, but the guts of it are accurate. If you do decide to switch over to this type of logic and you run into errors, it would be prudent to create a new stackoverflow question to work through the problem.

Worksheet Paste values/Save as then return the original file using vba

I have a workbook which performs several Excel-functions that depend on one variable and fills out itself. I have a loop to create those forms and save in a directory but before that I want to copy all and paste special so that formulas will be gone.
Sub SaveAs1()
For i = 172 To 225
Dim SaveName As Integer
SaveName = ActiveWorkbook.Sheets(1).Range("bi1").value
Application.ActiveWorkbook.SaveAs "C:\" & SaveName
Range("bi1") = i + 1
Next
End Sub
I figure that out finally using trial and error method
Sub Save()
Rem kaydetmece dongusu
For i = 172 To 180 Step 1
Application.DisplayAlerts = False
Workbooks.Open Filename:="C:\"
Range("bi1") = i + 1
Dim SaveName As Integer
SaveName = ActiveWorkbook.Sheets(1).Range("bi1").value
Range("A1:BE63").Select
Range("a1").Activate
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Application.ActiveWorkbook.SaveAs "C:\" & SaveName
Columns("BE:BU").Select
Selection.Delete Shift:=xlToLeft
Sheets("CAL").Select
ActiveWindow.SelectedSheets.Delete
Sheets("sahadan").Select
ActiveWindow.SelectedSheets.Delete
ActiveWorkbook.Close True
Next
End Sub
If you're asking how to paste values, this is how you do it. Replace "A1" with the actual range you need to use.
Range("A1").Copy
Range("A1").PasteSpecial xlPasteValues

Resources