Create a macro that copy and pastes data - vba

I'm trying to create a macro that opens a file and copy and pastes data from that file into a new excel sheet.
Problem is, the file is updated every month. So I have a sheet on excel where I have copy pasted the path to that file (Instructions and its in cell A2). I want to know how I can adjust my code to open that file, copy its data and close the file. I also want to create a button that I can press to run the macro.
This is my code so far:
Sub ImportData_Click()
'open the source workbook and select the source sheet
Workbooks.Open Filename:="'Instructions!'$A$2" 'this is the part of the
code that I'm having trouble with
Sheets("ABC").Select
' copy the source range
Sheets("ABC").Range("C:AI").Select
Selection.Copy
' select current workbook and paste the values
ThisWorkbook.Activate
Sheets("ABC DUMP").Select
Sheets("ABC DUMP").Range("A:").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
'close the source workbook
Windows("'Instructions!'$A$2").Activate
ActiveWorkbook.Close
End Sub

You have several minor syntax errors. With A2 data like:
C:\TestFolder\ABC.xls
this appears to work just fine:
Sub ImportData_Click()
'open the source workbook and select the source
Dim wb As Workbook
Workbooks.Open Filename:=Sheets("Instructions").Range("$A$2").Value
Set wb = ActiveWorkbook
Sheets("ABC").Select
' copy the source range
Sheets("ABC").Range("C:AI").Select
Selection.Copy
' select current workbook and paste the values
ThisWorkbook.Activate
Sheets("ABC DUMP").Select
Sheets("ABC DUMP").Range("A1").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
'close the source workbook
wb.Close
End Sub
This can be re-coded to avoid Select

If you define a variable as a string and then set it to equal your filename ('Instructions!'$A$2) you can then use this variable in the workbooks.open function.
Your workbooks.open function also requires a pathname for this workbook; therefore define another variable for your pathname and you should be able to use:
Workbooks.Open Filename:=PathName & Filename

Related

Paste Special VBA does not work in embedded excel workbook

I'm having an issue with the PasteSpecial function when working in an embedded excel workbook. The program I am working in is "Promax" which is block diagramming software running in Visio, which has the option to add an embedded excel workbook. I've essentially set up a number of cells in excel so that I can import a bunch of fields into a PDF form.
While working in the embedded workbook I am unable to get this function to give any output into the new excel worksheet. If I save a version of the workbook that is outside of promax, the code runs fine. If I just try to paste instead of paste special the code works fine, but all of the references that I pasted break in the new workbook.
Sub ExporttotxtFile()
Dim wb As Workbook
Dim saveFile As String
Dim WorkRng As Range
On Error Resume Next
Set WorkRng = Sheets("Sheet1").Range("A1:HK2")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wb = Application.Workbooks.Add
WorkRng.Copy
wb.Worksheets(1).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
wb.Worksheets(1).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
saveFile = Application.GetSaveAsFilename(InitialFileName:="Export", fileFilter:="Text Files (*.txt), *.txt")
wb.SaveAs Filename:=saveFile, FileFormat:=xlText, CreateBackup:=False
wb.Close
Application.CutCopyMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Does anyone have a solution to this or another method of getting this done? This code was taken from this: https://www.extendoffice.com/documents/excel/612-excel-export-data-to-text.html
Thanks!
While playing around with this more it seemed like xlPasteFormat was pasting an image over the values rather than formatting. I scrapped the pastespecial method and used a different solution.
wb.Worksheets(1).Paste
wb.Worksheets(1).Range("A1:HK2").Value = WorkRng.Value
I paste everything with the first paste and set the values with the second line so that the formatting stays.
Thanks for the help everyone.

VBA copy selection range in loop

I want to ask about loop in VBA. I have this VBA code:
Sub OpenCopyPaste()
' open the source workbook and select the source sheet
Workbooks.Open Filename:="C:\Users\Adryan Permana\Downloads\Test\part8.xlsx"
Sheets("Sheet1").Select
' copy the source range
Sheets("Sheet1").Range("C2:E2,C3:E3,C4:E4,C5:E5,C6:E6,C7:E7,C8:E8,C9:E9").Select
Selection.Copy
' select current workbook and paste the values starting at A1
Windows("report.xlsx").Activate
Sheets("Sheet1").Select
Sheets("Sheet1").Range("C3").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveWorkbook.Save
End Sub
I want to select all data in range "C2:E2" to "C9:E9" and paste it to other workbook.
In my current code, I need to type one by one range from C2 - C9.
I want to select data from C2-C9 in loop.
Is there any way to do it in loop?
You can copy the entire range with Range("C2:E9").Copy.
Also, there is no need to use Select, Activate and Selection, it slows down the code run-time, just use fully qulifed Wroksheets and Range instead.
Code
Option Explicit
Sub OpenCopyPaste()
Dim wb As Workbook
Dim Reportwb As Workbook
' set report workbook to workbook object (works only is the file is already open)
Set Reportwb = Workbooks("report.xlsx")
' open the source workbook and select the source sheet
Set wb = Workbooks.Open(Filename:="C:\Users\Adryan Permana\Downloads\Test\part8.xlsx")
' copy the source range and paste in 1 line , paste at "C3"
wb.Sheets("Sheet1").Range("C2:E9").Copy Destination:=Reportwb.Sheets("Sheet1").Range("C3")
Application.CutCopyMode = False
Reportwb.Save
End Sub
Instead use C2:E9
Sub OpenCopyPaste()
' open the source workbook and select the source sheet
Workbooks.Open Filename:="C:\Users\Adryan Permana\Downloads\Test\part8.xlsx"
Sheets("Sheet1").Select
' copy the source range
Sheets("Sheet1").Range("C2:E9").Select
Selection.Copy
' select current workbook and paste the values starting at A1
Windows("report.xlsx").Activate
Sheets("Sheet1").Select
Sheets("Sheet1").Range("C3").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveWorkbook.Save
End Sub

VBA MACRO unable to paste

Please help me... this is driving me nuts.
I am trying to copy some data from a CSV but unable to paste it to the destination file that I normally do manually.
The issue I am facing:
-I cannot go back to the destination file's sheet
-Even if I could it would paste as string
-I need the data to be identical from the CSV
MyFile = Application.GetOpenFilename()
ChDir "C:\datafolder\"
Application.Workbooks.Open (MyFile)
Range("A1").CurrentRegion.Select
Selection.copy
ActiveWorkbook.Close savechanges:=False
Application.ScreenUpdating = True
Windows("chickenfeed.xlsm").Activate
ActiveWorkbook.Sheets("Raw Export").Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End sub
You closed the source range before the paste.
Try this and learn the flow...
(Assuming it's "Sheet1" you try to copy data from)
Option Explicit
Sub PasteData()
Dim oSourceWB As Workbook, oTargetWB As Workbook, MyFile As String
MyFile = Application.GetOpenFilename()
ChDir "C:\datafolder\"
On Error Resume Next
Set oSourceWB = Workbooks.Open(Filename:=MyFile, ReadOnly:=True)
Set oTargetWB = Workbooks("chickenfeed.xlsm")
On Error GoTo 0
If Not (oSourceWB Is Nothing And oTargetWB Is Nothing) Then
oSourceWB.Worksheets("Sheet1").Range("A1").CurrentRegion.Copy oTargetWB.Sheets("Raw Export").Range("A1")
oSourceWB.Close SaveChanges:=False
End If
Set oSourceWB = Nothing
Set oTargetWB = Nothing
End Sub

Copying Data from a worksheet to another workbook

How to Copy data from one excel file to another file in different folder using VBA?
From the above link I got the codes that I was looking for.
My Query hasn't been solved yet.
I made few changes to the code to my requirements and still I get wrong results.
Below mentioned is the code that I used.
Sub TransferDataV2() 'transfer stuff from this workbook to workbook 2
Dim strPath2 As String
Dim wbkWorkbook1 As Workbook
Dim wbkWorkbook2 As Workbook
'define paths and filenames
strPath2 = "E:\Purchase Register 2015-16.xlsx"
'open files
Set wbkWorkbook1 = ThisWorkbook '### changed this
Set wbkWorkbook2 = Workbooks.Open(strPath2)
'copy the values across
'### change the sheet and range to what you need
wbkWorkbook1.Activate
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
wbkWorkbook2.Worksheets("Sheet1").Activate
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveCell.Offset(1).Select
ActiveCell.PasteSpecial
'close the workbook
wbkWorkbook2.Close (True)
End Sub
Now whenever I update some data in this workbook and try to save to another workbook, the copied data replaces the already available data in the strPath2 = "C:\put in this.xlsx".
The result I require is the copied data must be saved in the put in this.xlsx
but at the end of the table. Instead This code copies the data and saves them in from A2:G5. Kinldy Advice
After Selection.Copy try:
wbkWorkbook2.Worksheets("Sheet1").Cells(wbkWorkbook2.Worksheets("Sheet1").UsedRange.Row + 1, 1).PasteSpecial
'close the workbook
wbkWorkbook2.Close (True)

Simple Excel VBA macro failing

I have the following simple macro to copy data from a closed worksheet. The code runs fine from the VBA editor but fails with a subscript error when run from Excel via macro. The paste special statement appears to be the issue.
I just can't see where the problem is, can anyone help?
Dim wsMaster As Worksheet
Set wsMaster = Worksheets("Master Data")
Dim lastrow As Long
Dim Files As String
Files = "Download.xlsx"
Dim filepath As String
filepath = "C:\users\ms612533\desktop\"
Application.ScreenUpdating = False
wsMaster.Activate
Cells.Select
Selection.Clear
Workbooks.Open (filepath & Files)
lastrow = Worksheets("Global").UsedRange.Rows.Count
Worksheets("Global").Range("A1:V" & lastrow).Copy _
wsMaster.Range("B1")
Worksheets("Global").Range("CV1:cv" & lastrow).Copy
wsMaster.Range("a1").PasteSpecial (xlValues)**
Application.CutCopyMode = False
ThisWorkbook.Activate
Call CloseAll
Application.ScreenUpdating = True
End Sub
Sub CloseAll()
' Close all but the active workbook
Dim wkbk As Workbook
Application.ScreenUpdating = False
For Each wkbk In Application.Workbooks
If wkbk.Name <> ActiveWorkbook.Name Then
wkbk.Close SaveChanges:=False
End If
Next
Application.ScreenUpdating = True
End Sub
I think there's something wrong with the PasteSpecial line: when I use the macro recorder, I get something like this:
wsMaster.Range("a1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
I think we can ignore the parameters after the first. Then we have this:
wsMaster.Range("a1").PasteSpecial Paste:=xlPasteValues
Note that there are no parens (()) around the arguments: PasteSpecial doesn't return anything so it should be treated like a function. That's probably where the subscript issue is coming from.
Also notice the parameter, which comes from the xlPasteType enum, is a little different from the value you had.
The code appears to work fine when calling the macro from a button, but it doesn't work from a shortcut. I'll put it down to an Excel 'feature' and move on.