Excel Macro Automatic copy paste when opening the file - excel

We have 2 different files with basic vlookup infos:
Source file is: JP2-CSV CRAWLER
Destination file is: JP2-CATEGORIES
We are trying to copy one full column from the Source file to the first column of the destination file automatically ( It should work when opening it or using it)
That's our code:
Sub Copysubcat()
Dim wbSource As Workbook
Dim wbDestination As Workbook
Set wbSource = Workbooks.Open( _
Filename:="C:\Users\user\Desktop\crawler file\JP2-CSV CRAWLER.xlsx")
Set wbDestination = Workbooks("C:\Users\user\Desktop\crawler file\JP2-CATEGORIES.xlsx")
wbSource.Sheets("CSV Crawler").Range("P2:P10000").Copy
wbDestination.Sheets("Cats & Subcats").Range("A2:A10000").PasteSpecial (xlPasteValues)
Application.CutCopyMode = False
ActiveWorkbook.Save
End Sub
We are having an error "Subscript out of range"
Anybody could help on that?

Workbooks isn't a method, so it cannot take any parameters. This is class, which represents workbooks, which contains methods to handle them. One of them is Open which you will need in this case. So you'll need to switch this:
Set wbDestination = Workbooks("C:\Users\user\Desktop\crawler file\JP2-CATEGORIES.xlsx")
to this:
Set wbDestination = Workbooks.Open("C:\Users\user\Desktop\crawler file\JP2-CATEGORIES.xlsx")
Also, there is an event such as opening the workbook, you can place your corrected code there, so the macro would run every time this event is raised (i.e. on every opening). If you are using standard VBA development environment in Excel, click on This_workbook on right side (in tree view), you will have to dropdown lists at the top, in the one on the left choose Workbook, in the other one select Open (this is list of events, that is raised by Workbook). Then, inside generated method place youre code :)

Related

Application.Workbooks(V_WBNameOutPut).Activate alternative

I use this piece of code:
Application.Workbooks(V_WBNameOutPut).Activate
to activate a particular excel file, I notice that this method goes in error if the "File name extension" (in the View tab of the Folder Menu) is flagged.
In order to be independent of this, what modification should I do/include to the code or what alternative method should I use?
This answer is based on the comment
I interchange many times during the macro run between 2 workbooks, input and output
excel files, and I need to activate the V_WBNameOutPut, to paste and elaborate, and > this is done multiple times during the run. From the input file, I create the > V_WBNameOutPut file.
As #brax said - capture the workbook when it's opened and you don't have to worry about the extension after that.
Sub Test()
'Open the first workbook and store reference to it.
Dim wrkBk1 As Workbook
Set wrkBk1 = Workbooks.Open("H:\Darren Bartrup-Cook\Test 1.xlsx")
'Open the second workbook and store reference to it.
Dim wrkBk2 As Workbook
Set wrkBk2 = Workbooks.Open("H:\Darren Bartrup-Cook\Test 2.xlsx")
'Copy/paste from wrkbk1 to wrkbk2.
wrkBk1.Worksheets("Sheet1").Range("A1").Copy Destination:=wrkBk2.Worksheets("Sheet1").Range("A4")
'Create a new sheet in wrkbk2.
Dim NewWrkSht As Worksheet
Set NewWrkSht = wrkBk2.Worksheets.Add
NewWrkSht.Name = "My New Sheet"
'Paste copy/paste values from wrkbk1 to wrkbk2.
wrkBk1.Worksheets("Sheet1").Range("A2").Copy
NewWrkSht.Range("A5").PasteSpecial Paste:=xlPasteValues
'Make A3 in wrkbk2 equal the value in wrkbk1 A3.
wrkBk2.Worksheets("Sheet1").Range("A3") = wrkBk1.Worksheets("Sheet1").Range("A3")
'Close the two workbooks.
wrkBk2.Close SaveChanges:=True
wrkBk1.Close SaveChanges:=False
End Sub

How to get my assigned cell "Pathname" to open the master copy it is generated from. The information in the cell is accurate when generated

I have a "Master File" that generates a "field-generated" copy that at the push of a button is supposed to open the Master File and copy data back to it. The Field copy has a cell "ZZ1000" that has been titled "Pathname". When the field copy is generated the "Pathname" cell is filled out with the location of the master file. I have triple checked the "Pathname" is accurate, but when I hit the button I am receiving Run-time error '1004 Couldn't find the file.... However, during this it will still open the file, but will not allow the two files to communicate. When I debug this the third line highlight "Workbook.open" what can I do to avoid this? I am still fairly new to VBA so my trouble shooting skills are minimal at this point. Any direction would be appreciated.
Sub OpenWorkbook()
'Open a workbook
`'Open method requires full file path to be referenced.
Dim Pathname As String
Pathname = ThisWorkbook.Sheets("Field Copy").Range("Pathname").Formula
Workbooks.Open Pathname
ThisWorkbook.Unprotect "cost"
ThisWorkbook.Sheets("Field Copy").Visible = True
ThisWorkbook.Sheets("Field Copy").Visible = False
ThisWorkbook.Protect "cost"
With ActiveWorkbook
Workbooks("Field Copy.xlsx").Worksheets("Field Copy").Range("H5:BU52").Copy _
ThisWorkbook.Worksheets("Field Copy").Range("H5")
End With
End Sub

Cannot copy sheet to another workbook

I have what it seems a small issue but cannot figure out how to solve.
So, every week I have to make a bunch of pivot tables to summarize raw data that I am getting. I figured, it would be much easier if I create all the tables into a Layout file and then just copy them to the new file and then change the source. And I wrote the following code:
Sub something()
Workbooks.Open Filename:="C:\\\\Layout.xlsx"
With Workbooks("Layout.xlsx")
.Sheets("Pivot").Copy Before:=ActiveWorkbook.Sheets("Main List")
.Close savechanges:=False
End With
End Sub
This code works just fine. The issue comes when I try to paste the code into my personal workbook and then run through VBA directly, rather than copying and pasting it every time.
What I could do is, to change the code from 'Activeworkbook' to the name of my new workbook but its name change every week, because it is based on a date.
I already tried to declare the name of the new workbook as a string and call it through that but that didn't work either.
Any ideas?
I would use workbook objects to keep the two files clear:
Sub something()
Dim wb_from As Workbook, wb_to As Workbook
Set wb_to = ActiveWorkbook
Workbooks.Open Filename:="C:\\\\Layout.xlsx"
Set wb_from = Workbooks("Layout.xlsx")
wb_from.Sheets("Pivot").Copy Before:=wb_to.Sheets("Main List")
wb_from.Close SaveChanges:=False
end sub

Copy a text file and paste in excel

I was trying to copy a text file and paste the data in excel using the following code. The code works satisfactorily to the extent copying and pasting data in the destination excel sheet, but additionally, opens up another excel file and sheet with the same name as the Text file, without being prompted anywhere in the code, and pastes the data there as well. This is not desirable. I don't want to split the data to columns or perform any other actions. It is a plain and simple copy and paste task. I have searched this and various other websites for an answer but failed to get one that appropriately addresses my problem. I am unable to figure out the flaw in the code, and therefore, seek your help. Any help would be most thankfully acknowledged.
Here is my code:
Sub CopyTextFile()
Set TxtFileName = Workbooks.Open("D:\Spares\Inventory\list_of_spares.txt")
TxtFileName.Sheets(1).Range("A1").CurrentRegion.Copy
Workbooks("Macro Test.xlsm").Activate
ActiveWorkbook.Sheets(1).Range("A1").Select
ActiveSheet.Paste
End Sub
You're getting the "extra file" because you are opening the text file in Excel (with the Workbooks.Open statement) and then copying the data from it.
Instead, open the file with a filesystemobject and read the data, then write it directly into your workbook:
Sub CopyTextFile()
Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
Dim oFile : Set oFile = oFso.OpenTextFile("D:\Spares\Inventory\list_of_spares.txt", 1)
Dim sText
sText = oFile.ReadAll
oFile.Close
ThisWorkbook.Sheets(1).Range("A1").Value = sText
End Sub
See how that works for you?
I found a way to make your code work, you had to close the second workbook that was open, your code helped me thats why i am pointing out what was missing.
Sub CopyTextFile()
Set TxtFileName = Workbooks.Open("D:\Spares\Inventory\list_of_spares.txt")
TxtFileName.Sheets(1).Range("A1").CurrentRegion.Copy
Workbooks("Macro Test.xlsm").Activate
ActiveWorkbook.Sheets(1).Range("A1").Select
ActiveSheet.Paste
Workbooks(2).Close
End Sub
If you mention Workbooks(1).Close, it would close the first opened excel, here we want to close the second workbook hence Workbooks(2).Close
I found some excel vba code on this link which helped:https://www.excel-easy.com/vba/examples/close-open.html

Batch pasting data into excel

I have a load of data which I need to process. I process it by pasting the raw data into a pre-made excel spreadsheet, trimming a few rows of zeros at the bottom of the processing (not pasted in) columns, and then running a macro to remove cells with 0 in them in column P.
Each spreadsheet takes 6 sets of raw data, each in a separate worksheet. The zero-removing macro takes a while so I would like to do the pasting as a separate job if I can.
I feel like this should be pretty simple but unfortunately I only have a very basic knowledge of code. My idea so far has been to try and use AutoHotKey to record a sequence to do it, but unfortunately it is clunky and hasn't worked so far because alt-tabbing is unreliable or some other issue.
I would like to make a code which switches between windows, copying the data from one excel (tab delimited .txt) file into the main .xlsm document.
I would manually save it and then open the next 6 datasets and a blank processing workbook.
Thanks for your time x
Edit: The datasets are always called a,a1,a2,b,b1,b2. They are always located in the same folder as the data processing spreadsheet. The data processing spreadsheet is always called [processor.xlsm]
Edit2: This is where I am:
Sub ImportData1()
'Prevent windows asking about saving clipboard data
Application.DisplayAlerts = False
'select dataset a
Worksheets("SeqA Run1").Activate
Workbooks.Open Filename:=ThisWorkbook.Path & "\a.txt"
ActiveSheet.Range("A4:I1000").Copy
Windows("Surge Test Data Analysis Importer.xlsm").Activate
Range("A7").Select
ActiveSheet.Paste
''Close dataset
Windows("a.txt").Activate
ActiveWorkbook.Close
'Select dataset a1
Worksheets("SeqA Run2").Activate
Workbooks.Open Filename:=ThisWorkbook.Path & "\a1.txt"
ActiveSheet.Range("A4:I1000").Copy
Windows("Surge Test Data Analysis Importer.xlsm").Activate
Range("A7").Select
ActiveSheet.Paste
''Close dataset
Windows("a1.txt").Activate
ActiveWorkbook.Close
'(repeat several times)
'Re-enable windows prompts about clipboards etc
Application.DisplayAlerts = True
End Sub
You do not need to switch between windows. You have to get references to the worksheets, and use the references. The first thing to do is record a macro, and then do whatever you would do, manually. Stop recording, and then start modifying the resulting macro.
Then, in your macro,
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set wb1 = Workbooks("<The name of your target Workbook>")
Set wb2 = Workbooks("<The name of your source Workbook>")
Set ws1 = wb1.Worksheets("<The name of your target> Worksheet")
Set ws2 = wb2.Worksheets("<The name of your source> Worksheet")
ws2.UsedRange.Copy
ws1.Paste
You may need to paste at a specific location in your Target.
Repeating requires looping (e.g., For ... Next). If you provide more info on your case, it would be helpful.
Remember that assigning to a variable of type Worksheet should be preceded by Set.

Resources