How to copy a file and paste into another sheet - vba

I need to copy a file from external drive and paste it into my excel, I can able to browse a file but I cant paste those values into a new sheet...in a same excel
here my code :
Dim fileStr As String
Sub GetOpenFile()
fileStr = Application.GetOpenFilename()
Worksheets("Sheet2").TextBox1.Value = fileStr
End Sub
Sub Button3_Click()
Workbooks.Open fileStr
ActiveSheet.Paste
End Sub

You're trying to paste to the active sheet without having copied anything to begin with. Also, the active sheet probably isn't the sheet you want to paste to anyway.
Try this instead:
Sub Button3_Click()
Dim wbToCopy As Workbook
Set wbToCopy = Workbooks.Open(fileStr)
wbToCopy.Worksheets("Sheet1").Range("A1:H100").Copy
ThisWorkbook.Worksheets("Sheet1").Range("A1").PasteSpecial
wbToCopy.Close
End Sub
ThisWorkbook always refers to the workbook that your macro is running in

Related

Excel VBA Copy Range Transpose from Another Spreadsheet

I want to copy a range from a workbook and transpose it into my current sheet.
Why would I get a "Subscript out of range" error on this line:
Workbooks("Libraries\Documents\Book1.xlsx").Worksheets("Sheet1").Range("A1:A5").Copy
Sub PasteSpecial_Examples()
'https://stackoverflow.com/questions/8852717/excel-vba-range-copy-transpose-paste
'https://www.excelcampus.com/vba/copy-paste-cells-vba-macros/
Workbooks("Libraries\Documents\Book1.xlsx").Worksheets("Sheet1").Range("A1:A5").Copy
ActiveSheet.Range("A1").PasteSpecial Transpose:=True
End Sub
Excel only permits one workbook open with a certain filename at the same time, even if those workbooks exist in different directories (which they must, or they couldn't have the same filename).
The Workbooks collection's index is just the filename, not the fully-qualified path and name.
I'm not sure whether the first point is the reason for the second point, or whether the second point is the reason for the first point, but they will be related.
So your code should be:
Sub PasteSpecial_Examples()
Workbooks("Book1.xlsx").Worksheets("Sheet1").Range("A1:A5").Copy
ActiveSheet.Range("A1").PasteSpecial Transpose:=True
End Sub
Based on comments implying that you haven't yet opened Libraries\Documents\Book1.xlsx when you run your code, you could do this:
Sub PasteSpecial_Examples()
Dim wsDst As WorkSheet
Set wsDst = ActiveSheet
Workbooks.Open "Libraries\Documents\Book1.xlsx"
Workbooks("Book1.xlsx").Worksheets("Sheet1").Range("A1:A5").Copy
wsDst.Range("A1").PasteSpecial Transpose:=True
End Sub
which continues to refer to the workbook by its name.
Or, slightly better, do this:
Sub PasteSpecial_Examples()
Dim wbSrc As WorkBook
Dim wsDst As WorkSheet
Set wsDst = ActiveSheet
Set wbSrc = Workbooks.Open("Libraries\Documents\Book1.xlsx")
wbSrc.Worksheets("Sheet1").Range("A1:A5").Copy
wsDst.Range("A1").PasteSpecial Transpose:=True
End Sub
which assigns a Workbook object to refer to the newly opened workbook and then uses that object in the Copy statement.
Note: In this code "Libraries\Documents\Book1.xlsx" is a relative reference to the file, e.g. if the current directory was C:\Temp then it would look for the file C:\Temp\Libraries\Documents\Book1.xlsx. You should seriously consider using an absolute reference if possible.
I do it like this:
Dim Finfo As String
Dim FilterIndex As Long
Dim Title As String
Dim ExportFilename As Variant
Dim CopyBook As Workbook
Dim CopySheet As Worksheet
Dim MnthName As String
'Set up file filter
Finfo = "Excel Files (*.xls*),*.xls*"
'Set filter index to Excel Files by default in case more are added
FilterIndex = 1
' set Caption for dialogue box
Title = "Select a the DD Revenue Master file to Export to"
'get the Forecast Filename
ExportFilename = Application.GetOpenFilename(Finfo, FilterIndex, Title)
'Handle file Selection
If ExportFilename = False Then
'No Export File was Selected
MsgBox "No file was selected"
Else
'Check and see if this is a correct Export File
Workbooks.Open (ExportFilename)
Set CopyBook = ActiveWorkbook
Set CopySheet = CopyBook.Worksheets(1)
MsgBox "Valid File Selected."
Application.CutCopyMode = False
revenueSheet.Range("A1:BO500").Copy
CopyBook.Worksheets(1).Activate
CopyBook.Worksheets(1).Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
CopyBook.Worksheets(1).Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False 'erase the clipboard
'close your stuff that you dont want open
End If
End Sub
Don't forget to close your workbooks when you are done. I had to trim a bunch of code because my file launches into a large case select. But often you select a workbook, open it, select some data, copy it, and paste it, close the workbook. Happens alot. Hope this helps. I believe that I found that you had to activate the newly selected workbook to perform actions on it. You can always refer to the workbook with the code in it as ThisWorkbook
To avoid confusion and since they are used in a bunch of modules I have a global variables module with the following in it but you could do this at the top of the sub if you don't have a complex project.
Option Explicit
Public thisWB As Workbook
Public functionSheet As Worksheet
Public revenueSheet As Worksheet
Public salesSheet As Worksheet
Public scratchSheet As Worksheet
Public lastRow As Double
'**********************************************************
'This sub routine will be used to intialize public variables
'**********************************************************
Private Sub SetPublicVariables()
Set thisWB = ActiveWorkbook
Set functionSheet = thisWB.Worksheets("Data Functions")
Set revenueSheet = thisWB.Worksheets("DD Monthly Revenue")
Set salesSheet = thisWB.Worksheets("Salespersons")
Set scratchSheet = thisWB.Worksheets("ScratchSheet")
End Sub
I use this method alot . . . . . .
Oh, I call the public variable set up upon workbook open (you can find that method). In order to call a private sub you must use.
Application.Run "Global_Variables.SetPublicVariables"
'that is modulename.methodname if you want to pass arguments following
'Application.Run "modulename.methodname", arg1, arg2, etc.
Cheers, Happy coding - WWC

Excel Macro: Setting a variable for a workbooks location?

I need to write a macro script that will copy data from one xml workbook and paste the values to another workbook. I've written the below macro that works fine, but i need to run this every week for several different documents so it means i have to replace the document name for each run.
Here's what i have so far:
Sub copying()
''''''Section 1''''''
Workbooks("Results_2561").Activate 'workbook i'm copying from
Range("B27:B41").Select
Selection.Copy
Workbooks("Overall_Results").Activate 'workbook i'm pasting to
Range("G2").PasteSpecial
''''''Section 2''''''
Workbooks("Results_2561").Activate
Range("C27:C41").Select
Selection.Copy
Workbooks("Overall_Results").Activate
Range("C2").PasteSpecial
''''''Section 3''''''
Workbooks("Results_2561").Activate
Range("I28:I40").Select
Selection.Copy
Workbooks("Overall_Results").Activate
Range("G17").PasteSpecial
''''''Section 4''''''
Workbooks("Results_2561").Activate
Range("J28:J40").Select
Selection.Copy
Workbooks("Overall_Results").Activate
Range("C17").PasteSpecial
End Sub
...
and that's only half the script. Is there a way i can declare a variable at the start and set it as the Workbooks file path so i can call that instead of typing and retyping it over and over again?
Preferably without using something like
Dim book1 as Workbook
Set book1 = Workbooks.Open("C://Results_2561.xlsm")
..as this keeps opening and closing the document when i run the script.
Thanks
since you're only interested in copying values you could use this helper Sub
Sub CopyValues(rngToCopyFrom As Range, rngToCopyTo As Range)
With rngToCopyFrom
rngToCopyTo.Resize(.Rows.COUNT, .Columns.COUNT).Value = .Value
End With
End Sub
to be exploited in your main code like follows:
Sub main()
Dim wsTo As Worksheet
Set wsTo = Workbooks("Overall_Results").ActiveSheet '<--| set the worksheet to paste values to
With Workbooks("Results_2561").ActiveSheet '<--| reference the worksheet to copy values from
CopyValues .Range("B27:B41"), wsTo.Range("G2")
CopyValues .Range("C27:C41"), wsTo.Range("C2")
CopyValues .Range("I28:I40"), wsTo.Range("G17")
CopyValues .Range("J28:J40"), wsTo.Range("C17")
End With
End Sub
should your relevant workbooks have more than one sheet, then just substitute
ActiveSheet
with
Worksheets("myRelevantShetName") '<--|change "myRelevantShetName" to the actual name of the relevant worksheet in each workbook
First of all, you don't have to Activate workbook every time when you want to copy/paste something. Just declare it in Range() property, for example:
''''''Section 1''''''
Workbooks("Results_2561").Sheets(1).Range("B27:B41").Copy
Workbooks("Overall_Results").Sheets(1).Range("G2").PasteSpecial
You can set Workbook as variable like:
Sub copying()
Dim wb1 As Workbook, wb2 As Workbook
Set wb1 = Workbooks("Results_2561")
Set wb2 = Workbooks("Overall_Results")
''''''Section 1''''''
wb1.Sheets(1).Range("B27:B41").Copy
wb2.Sheets(1).Range("G2").PasteSpecial
End Sub
Finally, as #A.S.H suggested, you can add a file dialog where you point which files you want to use. I have put it in some function (don't forget to put it in the same project as your copying macro):
Function strPath() As String
Dim intResult As Integer
Application.FileDialog(msoFileDialogFilePicker).Title = "Select file"
intResult = Application.FileDialog(msoFileDialogFilePicker).Show
If intResult <> 0 Then
strPath = Application.FileDialog(msoFileDialogFilePicker).SelectedItems(1)
End If
End Function
So your final code for Section 1 would look like:
Sub copying()
Dim wb1 As Workbook, wb2 As Workbook
MsgBox "Show file to copy form."
Set wb1 = Workbooks.Open(strPath())
MsgBox "Show file to paste in."
Set wb2 = Workbooks.Open(strPath())
''''''Section 1''''''
wb1.Sheets(1).Range("B27:B41").Copy
wb2.Sheets(1).Range("G2").PasteSpecial
End Sub

Using VBA to copy a spreadsheet from a secondary workbook into the primary one

I need to take a spreadsheet and compare it with a spreadsheet from another workbook. I know that I can do this using VBA, but I will need to copy a spreadsheet from another workbook so that both spreadsheets will reside within the same workbook and be accessible for comparison. How do I copy a spreadsheet from one workbook into another using VBA?
You don't need to copy the worksheets over to compare them. Simply open both WorkBooks and and set reference to there WorkSheets.
Sub CompareWorkBooks()
Dim wbPending As Workbook
Dim wsPending As Worksheet
Set wbPending = Workbooks("Items Pending")
Set wsPending = wsPending.Worksheet("Items")
Dim wbRecieved As Workbook
Dim wsRecieved As Worksheet
Set wbRecieved = Workbooks("Items Recieved")
Set wsRecieved = Worksheet("Items")
End Sub
If you provide names for Workbooks & WorkSheets and provide column information, we can give you better answers in a shorter period of time. Don't be afraid to post your code either.
If you want a user to select the target workbook and worksheet:
Create a userform
Declare targetWorkbook and tartgetWorksheet at the top of the code module
Add a command button and a combo box
When the button is clicked a file dialog is opened
A reference is now set to the open file
The names of all the worksheets are added to the combo
Changing the combo box value will set the refernce to tartgetWorksheet
Option Explicit
Public targetWorkbook As Workbook
Public tartgetWorksheet As Worksheet
Private Sub CommandButton1_Click()
Dim targetWorkbook As Workbook
Dim ws As Worksheet
Set targetWorkbook = getTargetWorkbook
If targetWorkbook = Nothing Then
MsgBox "Sowmthing went wrong", vbCritical, "Try Again"
Else
For Each ws In targetWorkbook.Worksheets
ComboBox1.AddItem ws.Name
Next
End If
End Function
Function getTargetWorkbook() As Workbook
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
On Error Resume Next
Set getTargetWorkbook = Application.Workbooks.Open(.SelectedItems(1))
On Error GoTo 0
End With
End Function
Private Sub ComboBox1_Change()
Set tartgetWorksheet = targetWorkbook.Worksheets(ComboBox1.Value)
End Sub

EXCEL VBA: Copy Sheet from a workbook to another workbook in different location

I am trying to copy a whole sheet from one Excel file to a sheet in another. Following is the code I wrote which doesn't work. Please suggest changes.
Sub copyallwos()
Dim wkbSource As Workbook
Dim wkbDest As Workbook
Dim shttocopy As Worksheet
Dim wbname As String
Set wkbSource = Workbooks.Open("C:\Users\AV\Documents\New folder\SCADA Wos.xlsm")
Set wkbDest = Workbooks("C:\Users\AV\Documents\New folder\MASTER.xlsm")
'perform copy
Set shttocopy = wkbSource.Sheets("tt")
shttocopy.Copy
wkbDest.Sheets("SCADAWOs").Select
ActiveSheet.Paste
End Sub
Try this under 'perform copy
wkbSource.Sheets("tt").Copy After:=wkbDest.Sheets("SCADAWOs")
You can also insert the sheet before your "SCAD..." sheet, just change After:= to Before:=. Also, if you don't necessarily know a sheet name in the destination workbook, you can use After:=Wkbdest.sheets(sheets.count) which will instert it after the last Worksheet.

Copy every worksheet from one excel file to another

Having this, probably easy to solve problem, but without any programing skills its hard for me to crack...
I made an excel file with a button, a macro assigned to it.
What it should do :
Open another xls file, for which the user can search on harddrive
copy every sheet from the opened file
Paste it to the original file and close the one it was copied from.
So far I got this:
Sub Importfile()
Dim sFile As String
Dim wb As Workbook
sFile = Application.GetOpenFilename("*.xls,*.xls")
If sFile <> "False" Then
Set wb = Workbooks.Open(sFile)
'Copy and paste code , where I dont know what to do
wb.Close
End If
End Sub
Your example code is right, looking at the recorded macro code should have shown you how to use the worksheet.copy method. Using that you would just have to loop through all the worksheets in your newly opened workbook and copy them to your original workbook.
I've used a For Each, you could also just a plain For or any other sort of loop that you like.
Sub Importfile()
Dim sFile As String
Dim wb As Workbook
Dim ws As Worksheet
sFile = Application.GetOpenFilename("*.xls,*.xls")
If sFile <> "False" Then
Set wb = Workbooks.Open(sFile)
For Each ws In wb.Worksheets
ws.Copy before:=ThisWorkbook.Worksheets(1)
Next ws
wb.Close
End If
End Sub
The macro works fine for me! Please make sure that you have placed the code in the correct location.
In the image below "Book1" is your original sheet (the one you are copying sheets to) the macro code should be inserted into a "module" (the red square) and not any of the ones in the orange square. If you do not have a "module 1" (or any other) you need to insert a new one by looking in the "insert" menu at the top of the vba editor.