Excel crashes when I copy a cell within a macro - excel

I have a simple macro that opens a csv file and supposed to copy a cell in the working Workbook:
Sub macro1()
Dim build_w As Workbook
Dim build_s As Worksheet
Dim folder_st As String
Application.ScreenUpdating = False
folder_st = "c:\file.csv"
Set build_w = Application.Workbooks.Open(folder_st)
Set build_s = build_w.Sheets("build")
build_s.Range("A1").Copy
ActiveSheet.Paste Range("A284")
build_w.Close True
Application.ScreenUpdating = True
End Sub
If I comment out the line build_s.Range("A1").Copy everything is fine, but If I leave this in, Excel crashes every single time.
Any suggestions?

Are you aware that the ActiveSheet at the moment you paste is itself the build_s worksheet? This is the problem when working with stuff like Activesheet. It is always preferable to specify worksheet and workbook objects precisely, without counting on what is active at a given moment.
Eventually, to get the behavior you want, you should do:
build_s.Range("A1").Copy ThisWorkbook.ActiveSheet.Range("A284")

Have you tried handling any possible errors with:
On Error GoTo MyHandler
MyHandler:

PFB for the require code. CSV file cannot have multiple sheets so that's why it must be crashing. CSV files can have only one sheet in it, so no need to specify sheet name.
Sub macro1()
'Declared variables
Dim build_w As Workbook
Dim folder_st As String
'Disabling screen updates
Application.ScreenUpdating = False
'Initializing the file name
folder_st = "c:\file.csv"
'Opening the workbook
Set build_w = Workbooks.Open(folder_st)
'Copying the value of cell A1
Range("A1").Copy
'Selecting the cell A284
Range("A284").Select
'Pasting the copied value
ActiveSheet.Paste
'Saving the workbook by saving the .CSV file
build_w.Close True
'Enabling screen updates
Application.ScreenUpdating = True
End Sub

it's because upon opening csv file it becomes the Active workbook and its only worksheet the Active worksheet
you can exploit this at your advantage like follows:
Option Explicit
Sub macro1()
Dim folder_st As String
Application.ScreenUpdating = False
folder_st = "c:\file.csv"
With ActiveSheet '<--| reference your currently active sheet before opening csv file
Application.Workbooks.Open(folder_st).Sheets("build").Range("A1").Copy '<--| open csv file (and it becomes the Active Workbook) and reference its "build" sheet range "A1" and copy it...
.Range("A284").PasteSpecial '<--| paste it to your referenced sheet range A284
Application.CutCopyMode = False '<--| release clipboard
ActiveWorkbook.Close False '<--| close Active workbook, i.e. the csv file
End With
Application.ScreenUpdating = True
End Sub

Related

VBA- Trouble with a ActiveCell.FormulaR1C1

Thank you for taking the time to help. I have a macro that looks up a workbook. From the recalled workbook, I want cell A1 in "Book1" to = cell A1 in the recalled workbook. I then want to auto fill over to K1 and down to K20. However, the range of data that I want to transfer isnt doing so.
My goal is to have the range on "book1" = the range on the recalled workbook- that way when another parties edits the recalled workbook, "book1" will reflect those edits.
I know PQ could be a good option for this but I want to try this avenue first.
My macro:
Sub copydata()
Dim path As String
path = InputBox("Please input path")
Application.ScreenUpdating = False
Dim actualfile As Workbook
Set actualfile = ActiveWorkbook
Dim script As Object
Set script = CreateObject("Scripting.FileSystemObject")
Dim catalogue As Object
Set catalogue = script.GetFolder(path)
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
Dim textfile As Object
For Each textfile In catalogue.Files
Workbooks.Open textfile
Dim loadedfile As Workbook
Set loadedfile = ActiveWorkbook
Range("A1").Select
ActiveCell.FormulaR1C1 = "='loadedfile.Worksheets(1)'!RC"
Selection.AutoFill Destination:=Range("A1:K1"), Type:=xlFillDefault
Range("A1:K1").Select
Selection.AutoFill Destination:=Range("A1:K20"), Type:=xlFillDefault
Range("A1:K20").Select
Next textfile
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
End Sub
I tried setting "book1" as an active workbook and no success.
Edit: Replying to some questions-------------------------------------------
There is a workbook containing this code. Then there is the ActiveWorbook actualfile. Are these two the same?
No they are different. The macro linked is native to book1 (open through entire process)
What are the recalled workbook and Book1?
Excel workbooks
Where should these formulas refer to and where should they be written to i.e. there is no mention of the worksheets?
worksheet one for both workbooks
If you're writing to the same worksheet, then the only remaining references will be references to the last opened file.
I am writing to book1. In other words I want to type "=" in A1 on book1, and then double click A1 on the recalled workbook and hit enter. Then, on book1 cell A1, I want to remove $$ so i can autofill a range. That way any edits from the recalled worksheet will be reflected on book1.
Also, you need to close the files. Please do clarify. You can edit your post at any time.
I am a newbie- thank you for taking the time to help me see these issues with my code

Copy worksheet between workbooks and overwrite the current worksheet

I have written VBA code that opens up a destination workbook, copies one of the worksheets, and pastes it into the current workbook.
When I run it a second or third time etc... instead of overwriting the current worksheet, it creates a completely new one.
Ex: Worksheet is called "data", first time it transfers "data", second time "data(2)".
I have another worksheet that uses VLOOKUP function to look at some cells of this data worksheet, so it is crucial that it has correct name "data".
I thought about deleting the current (data) file before running the macro, but what if something crashes and I lose my worksheet? Is there a better solution?
NOTE: I am running the macro from the main workbook to get the sheet to be copied from the external workbook.
Sub UpdateT()
Dim wb As Workbook
Dim aw As Workbook
'Open 2nd Workbook
Set aw = Application.ActiveWorkbook
Set wb = Workbooks.Open(Filename:="C:\Users\yilmadu00\Desktop\T.xlsx")
'Copy To Different Workbook
wb.Sheets("data").Copy After:=aw.Sheets("Data1")
'Close 2nd Workbook
aw.Save
wb.Close
aw.Sheets("data").Visible = False
ActiveWorkbook.Protect ("Password")
End Sub
Function to check whether worksheet exists (credits to #ScottCrainer):
Function SheetExists(ws As String)
SheetExists = Not IsError(Application.Evaluate(ws & "!A1"))
End Function
NOTE:
It does have the issue: if A1 on the sheet contains an error it will return a false negative.
ActiveWorkbook vs ThisWorkbook, Sheets vs Worksheets
You have used 'Activeworkbook' and 'Sheet(s)' in the code so I played along.
But
Although you can have a third workbook to run the code from, I'm guessing you are running the code from a module in the 'ActiveWorkbook'. If this is true, it would be more correct to use 'ThisWorkbook' instead which always refers to the workbook that contains the code (module), to avoid accidentally running the code on a third workbook.
Sheet(s) refers to Worksheet(s) and Chartsheet(s), again I'm guessing there are no chartsheets involved in this code, therefore it would be more correct to use 'Worksheet(s)' instead of 'Sheet(s)'.
Sub UpdateT()
Const cStrPath As String = "C:\Users\yilmadu00\Desktop\T.xlsx"
Const cStrAfter As String = "Data1"
Const cStrName As String = "data"
Const cStrOld As String = "data_old"
Dim aw As Workbook '1st workbook, 'ActiveWorkbook'
Dim wb As Workbook '2nd workbook
Dim oWs As Sheet 'Each sheet in workbook 'aw'
Dim blnFound As Boolean 'True if sheet(cStrName) was found
Set aw = ActiveWorkbook 'Create a reference to the ActiveWorkbook
Set wb = Workbooks.Open(Filename:=cStrPath) 'Open 2nd Workbook
With aw
' .UnProtect ("Password")
'Check each sheet in workbook 'aw'.
For Each oWs In aw.Sheets
With oWs
'Check if there already is a sheet with the name 'cStrName'.
If .Name = cStrName Then
.Name = cStrOld 'Rename the sheet.
blnFound = True 'Sheet(cStrName) was found.
Exit For 'Immediately stop checking, there can only be one.
End If
End With
Next
End With
With wb
'Copy sheet from 2nd workbook ('wb') to workbook 'wa'.
.Sheets(cStrName).Copy After:=aw.Sheets(cStrAfter)
.Close 'Close 2nd workbook ('wb').
End With
With aw
With Application
If blnFound = True Then 'Sheet(cStrName) was found.
.DisplayAlerts = False 'Disable showing delete message.
aw.Sheets(cStrOld).Delete 'Delete old version of sheet.
.DisplayAlerts = True
End If
End With
.Sheets(cStrName).Visible = False 'Hide sheet named 'cStrName'
.Protect ("Password")
.Save 'Save workbook 'aw'.
End With
End Sub
The next time you want to do something with the sheet you have to unprotect it or the code will fail. Hidden sheets can be deleted with no problems.

Excel VBA Copy and Pasting Variable Selection (changing worksheets) to a new Workbook and saving as CSV

I nearly have this done, except nothing is being pasted. MY PROBLEM: The exporting and save functions seems to work as it creates a new workbook and saves, but it is empty.
I am having the user select which worksheet they want to extract a static range from (the variable is the worksheet). Each sheet is named by the week number (52 separate worksheets) plus a couple of background data sheets, which offsets the worksheet visible name from what excel calls the worksheet by 4. Meaning sheet1 is called "Labor", while sheet5 is called "1" - for the first week of the year.
Anyways, that variable is passed through the lstExportInvoiceWeek combobox by the user. from that selection, I want to copy a static range (BA6:BT200) and then paste it into a csv file.
Here is my code. The pasting isn't working. The new workbook is saving blank.
Private Sub cmbInvoicesExport_Click()
Application.ScreenUpdating = False
Dim CurrentFileName As String
CurrentFileName = ActiveWorkbook.Name
Debug.Print "Active File: " + CurrentFileName
Dim wsexport As String
wsexport = cboExportInvoiceWeek.Value
Worksheets(wsexport).Activate
Worksheets(wsexport).Unprotect
Range("BA6:BT200").Copy
Workbooks.Add Template:="Workbook"
Range("A1").Select
ActiveSheet.Paste
Dim file_name As Variant
file_name = Application.GetSaveAsFilename(FileFilter:="CSV (Comma delimited) (*.csv), *.csv")
If file_name <> False Then
ActiveWorkbook.SaveAs Filename:=file_name
MsgBox "File Saved!"
End If
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
Application.CutCopyMode = False
Workbooks(CurrentFileName).Activate
Application.ScreenUpdating = True
End Sub
Avoid using ActiveSheet Instead use Workbooks("YourWorkbook.xls").Worksheets("Sheet1").Activate
You need to reference the Workbook target to paste the data.

How to extract data from multiple closed excel workbooks for placing in a separate workbook in different worksheets through VBA?

(Beginner VBA coder here!)
Does anyone know how to extract multiple, specific cell data from multiple closed workbooks that have the same worksheet format?
I am currently tasked to copy very specific data from certain cells from many different and new (but same format) sources and transfer them into another group of specific cells in an existing masterlist with different worksheets.
This is the code I wished would help, but it is lacking in too many ways as compared to what I need...
Sub Importsheet()
Dim Importsheet As Worksheet
'import worksheet from a closed workbook
Sheets.Add Type:= _
'e.g. directory below
"C:\Users\Loli\Desktop\Testing1.xlsx"
End Sub
This code helps me get the sheets out of the closed source workbook but not the specifically placed cells in the closed source excel. It also can't paste the data in specifically placed cells in different sheets in the destination excel.
It is very difficult to completely understand your requirements as it seems like sometimes you want to copy a range and some other times a single cell, so to point you in the right direction my answer only shows how to open and copy the relevant Sheet into your master workbook to then be able to reference the cell/ranges you want
(I would once you get your data then delete the Worksheet, so that your master doesn't suddenly becomes massive in size):
Sub ImportSheet()
Dim sImportFile As String, sFile As String
Dim sThisBk As Workbook
Dim vfilename As Variant
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set sThisBk = ActiveWorkbook
sImportFile = Application.GetOpenFilename( _
FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Open Workbook") 'open dialog to choose the file you want, you can change this to loop through a folder if they are all in there.
If sImportFile = "False" Then 'check if a file was selected before importing
MsgBox "No File Selected!"
Exit Sub
Else
vfilename = Split(sImportFile, "\")
sFile = vfilename(UBound(vfilename))
Application.Workbooks.Open Filename:=sImportFile 'open the selected file
Set wbBk = Workbooks(sFile)
With wbBk
If SheetExists("Raw_Data") Then ' you should change this to the date, you can do this easily by using a variable such as if SheetExists(variableDate) then, where variableDate = "12/12/2017" or something similar
Set wsSht = .Sheets("Raw_Data")
wsSht.Copy before:=sThisBk.Sheets("Sheet1") 'copy the worksheet into your master
'WsSht.range("A1:B2").copy Destination:=sThisBk.Sheets("Temp").Range("A1").paste xlpastevalues 'use this to copy a specified range in this case A1:B2 to a sheet in master workbook called Temp A1
Else
MsgBox "There is no sheet with name :Raw_Data in:" & vbCr & .Name
End If
wbBk.Close SaveChanges:=False
End With
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Private Function SheetExists(sWSName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = Worksheets(sWSName)
If Not ws Is Nothing Then SheetExists = True
End Function

Creating CSV with VBA to much cells

I have an vba macro that should (after updating some values from an online xml) save one sheet to a CSV file. This works, but if I open the CSV file, I see this:
CHF,Swiss Franc,1.2352,,,
CNY,Yuan Renminbi,8.1803,,,
EUR,Euro,1,,,
GBP,Pound Sterling,0.8585,,,
HKD,Hong Kong Dollar,10.3617,,,
SGD,Singapore Dollar,1.7097,,,
USD,US Dollar,1.3361,,,
,,,,,
,,,,,
So the problem is that three empty colomns and two empty rows are also saved. I know this raises no problems after opening the CSV file in Excel, but in the program I import it, it does.
I did some research and found that this probably has to do with the UsedRange. But i could find no way to set the usedRange to a new value, or only save a small part of the sheet.
I probably can copy the range I want, open a new workbook, paste this range and save this to a file, but this seems a bit harder than it should be. And it does not guarantee that my UsedRange in this new workbook is not also to big.
Does anyone know how to set the usedrange or do the things I want another way? I am an absolute VBA amateur, so if I did strange things, thats the reason.
The rest of my code works fine, so the problem is only in the extra comma's in the saved file.
My VBA code is below:
Sub updateCurrencies()
'
' updateCurrencies Macro
'
' Keyboard Shortcut: Ctrl+e
'
Application.DisplayAlerts = False
Dim wb As Workbook
Dim ws As Worksheet
Dim file As String
file = "\\SBS2008\RedirectedFolders\jasper\Desktop\currencies.csv"
Sheets("Sheet1").Select
ActiveWorkbook.XmlMaps("Envelope_Map").DataBinding.Refresh
Set ws = Sheets("currencies")
ws.Select
ActiveWorkbook.RefreshAll
ws.SaveAs file, FileFormat:=6
Sheets("info").Select
Set wb = Workbooks.Open(file)
wb.Save
Sheets("info").Select
Call CloseAllWorkbooks
End Sub
Public Sub CloseAllWorkbooks()
Dim wb As Workbook
For Each wb In Workbooks
If (wb.Name = "currencies") Then
wb.Close True
Else
wb.Close False ' Or True if you want changes saved
End If
Next wb
End Sub
See the answer here by Daniel Cook
Convert xls File to csv, but extra rows added?
Sub CorrectUsedRange()
Dim values
Dim usedRangeAddress As String
Dim r As Range
'Get UsedRange Address prior to deleting Range
usedRangeAddress = ActiveSheet.UsedRange.Address
'Store values of cells to array.
values = ActiveSheet.UsedRange
'Delete all cells in the sheet
ActiveSheet.Cells.Delete
'Restore values to their initial locations
Range(usedRangeAddress) = values
End Sub

Resources