Macro to copy from one workbook to another - Not working - excel

Good day
I am trying to run a very simple code, where I open a workbook, copy column "a:a", open another workbook and paste it there. The issue i am facing is that the data is being copied from the second workbook into the second workbook, nothing is being copied from the first.
Code below for more clarity
Sub Copytocurrent()
strSecondFile = "Z:\AR\AR PROGRESS\2014\MENACA REPORTS\0MENACA Working File\AR Working File\UAE\RECEIVABLE.xls"
strThirdFile = "Z:\AR\AR PROGRESS\2014\MENACA REPORTS\0MENACA Working File\AR Working File\UAE\Working File - UAE.xlsx"
Set wbk2 = Workbooks.Open(strSecondFile)
Set wbk3 = Workbooks.Open(strThirdFile)
'-------------------------------------------------------'
'Copy column A in Receivable to Column XB in Working File'
'-------------------------------------------------------'
Application.CutCopyMode = False
wbk2.Sheets("receivable").Activate
With wbk2.Sheets("receivable")
Range("a:a").Copy
End With
wbk3.Sheets("Sheet1").Activate
With wbk3.Sheets("sheet1")
Range("XB1").PasteSpecial
End With
'-------------------------------------------------------'
'Copy column B in Receivable to Column XA in Working File'
'-------------------------------------------------------'
Application.CutCopyMode = False
wbk2.Sheets("receivable").Activate
With wbk2.Sheets("receivable")
Range("b:b").Copy
End With
wbk3.Sheets("Sheet1").Activate
With wbk3.Sheets("sheet1")
Range("XA1").PasteSpecial
End With
wbk2.Close True
wbk3.Close True
End Sub

Try this, activate Workbook objects accordingly like you would do in a real copypaste flow. I run this method in a third xlsm workbook.
Public Sub testCopy()
Dim wb1 As Workbook
Dim wb2 As Workbook
Set wb1 = Workbooks.Open("C:\projects\excel\book1.xlsx")
Set wb2 = Workbooks.Open("C:\projects\excel\book2.xlsx")
Application.CutCopyMode = False
wb1.Activate
With wb1.Sheets("Sheet1")
Range("A:A").Copy
End With
wb2.Activate
With wb2.Sheets("Sheet1")
Range("E1").PasteSpecial
End With
Application.CutCopyMode = False
wb1.Activate
With wb1.Sheets("Sheet1")
Range("B:B").Copy
End With
wb2.Activate
With wb2.Sheets("Sheet1")
Range("F1").PasteSpecial
End With
wb1.Close True
wb2.Close True
End Sub
edit: ok I was late you discovered the same fix by yourself a second before my post.

As you already identified, you're issue was that you're using the activeworkbook for the copying, but forget to use .Activate. Better than using ActiveWorkbook, try accessing the ranges directly. This makes the code more robust - and less bloated:
Sub CopyToCurrent()
Dim wbkSource As Workbook, wbkTarget As Workbook 'Alays Dim your variables to prevent errors from typos!
Dim wsSource As Worksheet, wsTarget As Worksheet
Application.ScreenUpdating = False 'Prevent screen flickering
Set wbkSource = Workbooks.Open("Z:\AR\AR PROGRESS\2014\MENACA REPORTS\0MENACA Working File\AR Working File\UAE\RECEIVABLE.xls")
Set wbkTarget = Workbooks.Open("Z:\AR\AR PROGRESS\2014\MENACA REPORTS\0MENACA Working File\AR Working File\UAE\Working File - UAE.xlsx")
Set wsSource = wbkSource.Sheets("receivable")
Set wsTarget = wbkTarget.Sheets("Sheet1")
wsSource.Range("A:A").Copy
wsTarget.Range("XB1").PasteSpecial
wsSource.Range("B:B").Copy
wsTarget.Range("XA1").PasteSpecial
wbkSource.Close False 'No need to save any changes
wbkTarget.Close True
Application.ScreenUpdating = True
End Sub
Note that I also added some small improvements (Dimming, prevent screenflickering)

Related

Unwanted worksheet duplication VBA

I built a code into a command button that identified a single sheet, copies the values and the formulas, and creates a separate detached workbook that we use for ordering material. The original formula worked great and was simple when there was only 1 target sheet. I have added 4 additional sheets to be captured, the core of the formula still works and it copies/detaches a separate workbook for ordering, but now it is also creating a copy of the original workbook as well for no reason.
How can I get it to only copy and detach the sheets in the formula and not the entire workbook?
Private Sub CommandButton1_Click()
' Plain_Copy Macro '
Sheets("PROCUREMENT").Visible = True
Sheets("Request").Visible = True
Sheets("LISTS").Visible = True
Sheets("Copy").Visible = True
Dim TheActiveWindow As Window
Dim TempWindow As Window
Dim ws As Worksheet
With ActiveWorkbook
Set TheActiveWindow = ActiveWindow
Set TempWindow = .NewWindow
.Sheets(Array("REQUESTOR", "PROCUREMENT", "Request", "LISTS", "Copy")).Copy
Application.ScreenUpdating = False
For Each ws In ActiveWorkbook.Worksheets
With ws.UsedRange
.Copy
.PasteSpecial xlPasteFormulasAndNumberFormats
End With
TempWindow.Close
Next ws
Application.CutCopyMode = False
Application.ScreenUpdating = True
End With

Replace formulas with values and save it as a new file and change original file back to formulas afterwards

I have an Excel-File in which the user can click on a button to save a version without formulas and only with values.
So far I use this VBA for it:
Sub Create_version_with_values_only()
Dim b As Worksheet
For Each b In Worksheets
b.Cells.Copy
b.Cells.Cells.PasteSpecial Paste:=xlPasteValues
Next b
Application.CutCopyMode = False
ActiveWorkbook.SaveCopyAs "G:\Folder\test.xlsm"
ThisWorkbook.Close SaveChanges:=False
End Sub
This VBA itself worsk fine.
However, the issue is that I have to close the file after the value-version of the file is created because the original version will not be available anymore.
Therefore, I am wondering if there is an alternative way to create the value-version of the file that makes it possible to go back to the original file afterwards.
Something like this:
Step 1) Change all formulas to values.
Step 2) Save the version with the values in the folder.
Step 3) Undo the value-replacements in original sheet without closing it.
Do you have any idea how to solve it?
There might be a more simple way to get there, but here's how you'd create a new workbook, transfer the values over and save.
Public Sub SaveValues()
Dim newWb As Workbook
Set newWb = Workbooks.Add 'create a new workbook for the values
Dim ws As Worksheet, newWs As Worksheet
For Each ws In ThisWorkbook.Worksheets
With newWb 'create worksheets and name them in new workbook
If ws.Index = 1 Then
Set newWs = .Worksheets(1)
Else
Set newWs = .Worksheets.Add(After:=.Worksheets(.Worksheets.Count))
End If
newWs.Name = ws.Name
End With
With ws.UsedRange 'move values to new worksheet
newWs.Range("A1").Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
Next
'save new workbook. If the current workbook is a .xlsb, change the .xlsm in the code below
newWb.SaveAs Replace(ThisWorkbook.FullName, ".xlsm", "_hardcoded.xlsm"), xlOpenXMLWorkbookMacroEnabled
newWb.Close
End Sub
Updated for alternatives below:
Alternative
An alternative is to use ThisWorkbook.Worksheets.Copy to copying all worksheets in one go. Unfortunately, to use this code, we have to use ActiveWorkbook to make a reference to the new workbook. (I hoped it might return a Workbook or Worksheets object)
Public Sub SaveValues2()
Dim newWB As Workbook
ThisWorkbook.Worksheets.Copy
Set newWB = ActiveWorkbook 'not great practice
Dim ws As Worksheet
For Each ws In newWB.Worksheets
With ws.UsedRange 'hardcode values
.Value = .Value
End With
Next
newWB.SaveAs Replace(ThisWorkbook.FullName, ".xlsm", "_hardcoded.xlsm"), xlOpenXMLWorkbookMacroEnabled
newWB.Close
End Sub

VBA won't copy the next table, but keeps pasting the first instead

I have the following code
Sub Workbook_Open()
Dim x As Workbook
Dim y As Workbook
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Application.AlertBeforeOverwriting = False
Set x = ThisWorkbook
Set y = Workbooks.Open("N:\\REAL PATH")
'Opens Data and Pastes Values
x.Worksheets("Event Data").Range("Table1[#All]").Copy
y.Worksheets("CoreData").Range("A1").PasteSpecial Paste:=xlPasteValues
x.Worksheets("Comments").Range("Table2[#All]").Copy
y.Worksheets("CommentsData").Range("A1").PasteSpecial Paste:=xlPasteValues
x.Worksheets("Match Data").Range("Table3[#All]").Copy
y.Worksheets("MatchDetails").Range("A1").PasteSpecial Paste:=xlPasteValues
y.Close SaveChanges:=True
ActiveWorkbook.Save
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
After running the code, I go to the workbook named y, and I find that Table 1's data has been pasted three times. So, basically, the y.Worksheets lines are working properly but it won't copy data from Table 2 or 3. If I hit ctrl + g and type in "Table2[#All]" I am taken to the full Table 2, so I know that the range exists and that VBA should be able to find it. Table 1 contains quite a bit of data (131k rows + columns to DZ), but I don't know if that's relevant.
I find that creating and using intermediate variables greatly helps to clear up any problems in transferring data. Plus, you can look at these variables when debugging to verify they are correctly set.
Try something along these lines:
Option Explicit
Sub Example()
Dim srcWB As Workbook
Dim dstWB As Workbook
Set srcWB = ThisWorkbook
Set dstWB = Workbooks.Open("N:\\REAL PATH")
Dim srcData As Range
Dim dstData As Range
Set srcData = srcWB.Sheets("Event Data").Range("Table1[#All]")
Set dstData = dstWB.Sheets("CoreData").Range("A1").Resize(srcData.Rows.Count, _
srcData.Columns.Count)
dstData.Value = srcData.Value
Set srcData = srcWB.Sheets("Comments").Range("Table2[#All]")
Set dstData = dstWB.Sheets("CommentsData").Range("A1").Resize(srcData.Rows.Count, _
srcData.Columns.Count)
dstData.Value = srcData.Value
Set srcData = srcWB.Sheets("Match Data").Range("Table3[#All]")
Set dstData = dstWB.Sheets("MatchDetails").Range("A1").Resize(srcData.Rows.Count, _
srcData.Columns.Count)
dstData.Value = srcData.Value
dstWB.Close SaveChanges:=True
End Sub
You've also confused using ThisWorkbook and later using ActiveWorkbook. It's not clear which on you're saving.
This type of "value only" data copy is very fast, and you may not need to disable events or screen updates. You still may need to disable these if you also have event handlers catching worksheet changes.

Excel VBA copy content from one Sheet into other Workbook sheet

I want to be able to select a workbook and then copy the content from that workbook (sheet 1) into my current active workbook where I run the macro. I've been looking at some answers here on StackOverflow to similar questions and got the following code (see below).
The selection of a file is currently working fine, but when I run the macro it throws an error
Runtime error "438": Object does not support that method or property`
(please note, that the error comes in my native language and is just translated by me)
Sadly no object is marked that he relates to, so I can't really make out what problem he has. Yet, I guess it is a problem with the PasteSpecial in the last line of function GetTemplateData, but that code should be alright (what is it supposed to do? Save the data into the first sheet of the give workbook activeWorkbook) and pass the reference back go GeneratedValues-routine.
Option Explicit
Private Sub GenerateValues()
'Application.ScreenUpdating = False
'Application.DisplayAlerts = False
Dim activeWorkbook As Workbook
Dim activeWorksheet As Worksheet
Set activeWorkbook = Application.activeWorkbook
Set activeWorksheet = GetTemplateData(activeWorkbook)
activeWorkbook.Save
End Sub
'Get The Template Data
Private Function GetTemplateData(activeWorkbook As Workbook) As Worksheet
Dim templateWorkbook As Workbook
'Grab the Template Worksheet
Set templateWorkbook = UseFileDialogOpen
'Select all Content
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Copy
'activeWorkbook.Sheets(activeWorkbook.Sheets.Count).Range("A1", Cells.End(xlDown) & Cells.End(xlRight)).PasteSpecial xlPasteValues
activeWorkbook.Sheets(1).Range("A1", Cells.End(xlDown) & Cells.End(xlRight)).PasteSpecial xlPasteValues
End Function
'From https://learn.microsoft.com/de-de/office/vba/api/excel.application.filedialog
'Select the Workbook containing the Exported Template-Stories by User Selection
Function UseFileDialogOpen() As Workbook
Dim lngCount As Long
Dim filePath As String
Dim templateBook As Workbook
' Open the file dialog
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
Set templateBook = Workbooks.Open(.SelectedItems(1))
' Display paths of each file selected
'For lngCount = 1 To .SelectedItems.Count
' MsgBox .SelectedItems(lngCount)
'Next lngCount
End With
templateBook
End Function
I believe all of your problems originate here:
Private Sub GenerateValues()
'Application.ScreenUpdating = False
'Application.DisplayAlerts = False
Dim activeWorkbook As Workbook
Dim activeWorksheet As Worksheet
Set activeWorkbook = Application.activeWorkbook
Set activeWorksheet = GetTemplateData(activeWorkbook)
activeWorkbook.Save
End Sub
ActiveWorkbook is a defined "variable" in VBA, so it is confused as to why you are trying to reassign it. Try using a different variable name instead.
Note: although ActiveWorksheet is not a defined variable in VBA, it is close in name to ActiveSheet, so I would also change that variable name to something different just so to not confuse you when writing future code.
You could try something similar to this:
Sub CopyContentsFromOtherWorkbook()
Dim wb As Workbook
Dim twb As Workbook
filePath = "C:\File.xlsx"
Set wb = Workbooks.Open(filePath)
wb.Sheets(1).Range("A1:Z10000").Copy
Set twb = ThisWorkbook
twb.Sheets(1).Range("C1").PasteSpecial xlPasteValues
wb.Close
twb.Save
End Sub

Excel unable to access file

Just doing something at work, and trying to reference a file on a network directory on VBA.
Sub CostPriceMain()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
NewFile = Application.GetOpenFilename(FileFilter:="Microsoft Excel Files
(*.xlsx; *.xls), (*.xlsx; *.xls), All Files, *.*", FilterIndex:=1)
If NewFile = False Then Exit Sub
If NewFile <> False Then
Set wkbk = Workbooks.Open(NewFile)
End If
Dim Sh As Worksheet
For Each Sh In wkbk.Worksheets
If Sh.Visible = True Then
Sh.Activate
Sh.Cells.Copy
Workbooks("S:\Stafford\WK24 WH.xls").Sheets("Name").Range("A1").PasteSpecial Paste:=xlValues
End If
Next Sh
Application.CutCopyMode = False
ActiveWorkbook.Close True
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Done = MsgBox("Task Complete", vbOKOnly)
End Sub
I'm trying to open it so that that I can paste data from wkbk into it. However I keep getting a 'Microsoft Office Excel cannot access the file' runtime error 1004.
Is this an issue because the file is not stored locally? As I'm scratching my head at this.
Try this:
Sub CostPriceMain()
Dim SourceWkb As Workbook
Dim TargetWkb As Workbook
Dim SourceWksht As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
NewFile = Application.GetOpenFilename(FileFilter:="Microsoft Excel Files (*.xlsx; *.xls), (*.xlsx; *.xls), All Files, *.*", FilterIndex:=1)
If NewFile = False Then Exit Sub
If NewFile <> False Then
Set SourceWkb = Workbooks.Open(NewFile)
End If
Set TargetWkb = Workbooks.Open("S:\Stafford\WK24.xls") ' warning - XLS file could cause problems - see note
For Each SourceWksht In SourceWkb.Worksheets
If SourceWksht.Visible Then
SourceWksht.Copy After:=TargetWkb.Sheets(TargetWkb.Sheets.Count)
End If
Next SourceWksht
TargetWkb.Close True
SourceWkb.Close False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Done = MsgBox("Task Complete", vbOKOnly)
End Sub
I notice your "wk24" is an XLSfile, yet you invite the user to choose XLSor XLSX files to import from. You can't import an XLSX file into an XLS file using this method. I'd suggest changing your target file to WK24.XLSX
You open your workbook within the loop which means it will try and open it for every sheet - and throw an error when it's already open.
Open the workbook before you start looping and then just reference it. This code will copy each visible sheet from the workbook containing the code to WK24.xls (note, no activating of sheets required):
Sub Test()
Dim wrkBk As Workbook
Dim wrkSht As Worksheet
Set wrkBk = Workbooks.Open("S:\Stafford\WK24.xls")
For Each wrkSht In ThisWorkbook.Worksheets
If wrkSht.Visible Then
'Copy sheet.
wrkSht.Copy After:=wrkBk.Sheets(wrkBk.Sheets.Count)
End If
Next wrkSht
End Sub
Edit:
I've made a few changes to your posted code.
I removed If NewFile = False Then Exit Sub - If NewFile isn't false it will run the code, otherwise it jumps straight to the end. It provides a single exit point for your procedure.
I updated ActiveWorkbook.Close True to your referenced workbooks. ActiveWorkbook may not always be the correct book - always best to avoid Active or Select... if you find yourself using either (or Activate or Selected or anything similar) then you're probably making more work for yourself.
Your MsgBox isn't going to act on any response, it's just informing you so no need to set it to a variable.
If you're still finding it says the workbook isn't accessible then triple check the file location, file name, whether it's already open.
Which file is causing the problem? NewFile or WK24?
Also - are you copying the whole sheet, cells from the sheet, copy & pastespecial - you keep changing your code.
Sub CostPriceMain()
Dim NewFile As Variant
Dim wkbk As Workbook
Dim wrkBk As Workbook
Dim wrkSht As Worksheet
NewFile = Application.GetOpenFilename(FileFilter:="Microsoft Excel Files (*.xlsx; *.xls), (*.xlsx; *.xls), All Files, *.*", FilterIndex:=1)
If NewFile <> False Then
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wkbk = Workbooks.Open(NewFile)
Set wrkBk = Workbooks.Open("S:\Stafford\WK24.xls")
For Each wrkSht In wkbk.Worksheets
If wrkSht.Visible Then
'Copy all cells with formula, etc.
'wrkSht.Cells.Copy Destination:=wrkBk.Worksheets("Sheet1").Range("A1")
'Copy and pastespecial all cells.
'wrkSht.Cells.Copy
'wrkBk.Worksheets("Sheet1").Range("A1").PasteSpecial xlPasteValues
'Copy whole sheet to WK2 (Sheets includes ChartSheets)
wrkSht.Copy After:=wrkBk.Sheets(wrkBk.Sheets.Count)
End If
Next wrkSht
wrkBk.Close True 'Closes WK24.
wkbk.Close False 'Closes your chosen file without saving.
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "Task Complete", vbOKOnly
End If
End Sub

Resources