I have an Excel workbook, which using VBA code that opens another workbook, copies some data into the original, then closes the second workbook.
When I close the second workbook (using Application.Close), I get a prompt for:
Do you want to save the clipboard.
Is there a command in VBA which will bypass this prompt?
I can offer two options
Direct copy
Based on your description I'm guessing you are doing something like
Set wb2 = Application.Workbooks.Open("YourFile.xls")
wb2.Sheets("YourSheet").[<YourRange>].Copy
ThisWorkbook.Sheets("SomeSheet").Paste
wb2.close
If this is the case, you don't need to copy via the clipboard. This method copies from source to destination directly. No data in clipboard = no prompt
Set wb2 = Application.Workbooks.Open("YourFile.xls")
wb2.Sheets("YourSheet").[<YourRange>].Copy ThisWorkbook.Sheets("SomeSheet").Cells(<YourCell")
wb2.close
Suppress prompt
You can prevent all alert pop-ups by setting
Application.DisplayAlerts = False
[Edit]
To copy values only: don't use copy/paste at all
Dim rSrc As Range
Dim rDst As Range
Set rSrc = wb2.Sheets("YourSheet").Range("YourRange")
Set rDst = ThisWorkbook.Sheets("SomeSheet").Cells("YourCell").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
rDst = rSrc.Value
If I may add one more solution: you can simply cancel the clipboard with this command:
Application.CutCopyMode = False
I have hit this problem in the past - from the look of it if you don't actually need the clipboard at the point that you exit, so you can use the same simple solution I had. Just clear the clipboard. :)
ActiveCell.Copy
If you don't want to save any changes and don't want that Save prompt while saving an Excel file using Macro then this piece of code may helpful for you
Sub Auto_Close()
ThisWorkbook.Saved = True
End Sub
Because the Saved property is set to True, Excel responds as though the workbook has already been saved and no changes have occurred since that last save, so no Save prompt.
There is a simple work around. The alert only comes up when you have a large amount of data in your clipboard. Just copy a random cell before you close the workbook and it won't show up anymore!
Just clear the clipboard before closing.
Application.CutCopyMode=False
ActiveWindow.Close
proposed solution edit works if you replace the row
Set rDst = ThisWorkbook.Sheets("SomeSheet").Cells("YourCell").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
with
Set rDst = ThisWorkbook.Sheets("SomeSheet").Range("YourRange").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
Related
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 :)
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
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.
I am using this function to copy a sheet from a Workbook to another Workbook.
I works, but it seems that if I disable the macros from Workbook,
it can not copy the sheet anymore.
If I chage this line : m_objExcel.AutomationSecurity = msoAutomationSecurityForceDisable
to this m_objExcel.AutomationSecurity = msoAutomationSecurityByUI
it works but gets a warning message.
Also if I comment the line it works perfectly but with macros On.
Private Sub CopyFunction()
Set m_objExcel = New Excel.Application 'creare obiect
m_objExcel.DisplayAlerts = False
g_secAutomation = m_objExcel.AutomationSecurity
m_objExcel.AutomationSecurity = msoAutomationSecurityForceDisable
m_objExcel.Visible = True
Dim CopyFrom As Workbook
Dim CopyTo As Workbook
Dim CopyThis As Object
Set CopyFrom = m_objExcel.Workbooks.Open("D:\FromFile.xls")
Set CopyTo = m_objExcel.Workbooks.Open("D:\ToFile.xls")
Set CopyThis = CopyFrom.Sheets(1) ''Sheet number 1
CopyThis.Copy After:=CopyTo.Sheets(1)
m_objExcel.Workbooks(CopyTo.FullName).Save
CopyFrom.Close
CopyTo.Close
m_objExcel.Workbooks.Close
MsgBox "ok"
End Sub
I am using it from Access and work with a Excel file.
What is the problem?
Is there a way to still be able to copy a sheet from a workbook to another, and have the macros disabled?
That's what the disable macro is typically for: Security.
It is meant for your own protection; in case you receive a workbook from an unknown author, this person may want to send you harmful software.
Imagine for example that code starts deleting files as soon as you open the workbook.
Disabling macro's prevents this and allows you to look into code before you decide to execute it.
As a solution, the user can trust you as author while you sign your project as developer.
I suggest that you check out this link:
http://msdn.microsoft.com/en-us/library/aa190098(v=office.10)
(You can decide to turn off the security entirely (Enable macro's), but this is generally not recommended.)
I found that the problem is here:
m_objExcel.Workbooks(CopyTo.Name).Save
I want to search through existing Excel files with a macro, but I don't want to display those files when they're opened by the code. Is there a way to have them open "in the background", so to speak?
Not sure if you can open them invisibly in the current excel instance
You can open a new instance of excel though, hide it and then open the workbooks
Dim app as New Excel.Application
app.Visible = False 'Visible is False by default, so this isn't necessary
Dim book As Excel.Workbook
Set book = app.Workbooks.Add(fileName)
'
' Do what you have to do
'
book.Close SaveChanges:=False
app.Quit
Set app = Nothing
As others have posted, make sure you clean up after you are finished with any opened workbooks
If that suits your needs, I would simply use
Application.ScreenUpdating = False
with the added benefit of accelerating your code, instead of slowing it down by using a second instance of Excel.
To open a workbook as hidden in the existing instance of Excel, use following:
Application.ScreenUpdating = False
Workbooks.Open Filename:=FilePath, UpdateLinks:=True, ReadOnly:=True
ActiveWindow.Visible = False
ThisWorkbook.Activate
Application.ScreenUpdating = True
Using ADO (AnonJr already explained) and utilizing SQL is possibly the best option for fetching data from a closed workbook without opening that in conventional way. Please watch this VIDEO.
OTHERWISE, possibly GetObject(<filename with path>) is the most CONCISE way. Worksheets remain invisible, however will appear in project explorer window in VBE just like any other workbook opened in conventional ways.
Dim wb As Workbook
Set wb = GetObject("C:\MyData.xlsx") 'Worksheets will remain invisible, no new window appears in the screen
' your codes here
wb.Close SaveChanges:=False
If you want to read a particular sheet, need not even define a Workbook variable
Dim sh As Worksheet
Set sh = GetObject("C:\MyData.xlsx").Worksheets("MySheet")
' your codes here
sh.Parent.Close SaveChanges:=False 'Closes the associated workbook
A much simpler approach that doesn't involve manipulating active windows:
Dim wb As Workbook
Set wb = Workbooks.Open("workbook.xlsx")
wb.Windows(1).Visible = False
From what I can tell the Windows index on the workbook should always be 1. If anyone knows of any race conditions that would make this untrue please let me know.
Even though you've got your answer, for those that find this question, it is also possible to open an Excel spreadsheet as a JET data store. Borrowing the connection string from a project I've used it on, it will look kinda like this:
strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & objFile.Path & ";Extended Properties=""Excel 8.0;HDR=Yes"""
strSQL = "SELECT * FROM [RegistrationList$] ORDER BY DateToRegister DESC"
Note that "RegistrationList" is the name of the tab in the workbook. There are a few tutorials floating around on the web with the particulars of what you can and can't do accessing a sheet this way.
Just thought I'd add. :)
The problem with both iDevlop's and Ashok's answers is that the fundamental problem is an Excel design flaw (apparently) in which the Open method fails to respect the Application.ScreenUpdating setting of False. Consequently, setting it to False is of no benefit to this problem.
If Patrick McDonald's solution is too burdensome due to the overhead of starting a second instance of Excel, then the best solution I've found is to minimize the time that the opened workbook is visible by re-activating the original window as quickly as possible:
Dim TempWkBk As Workbook
Dim CurrentWin As Window
Set CurrentWin = ActiveWindow
Set TempWkBk = Workbooks.Open(SomeFilePath)
CurrentWin.Activate 'Allows only a VERY brief flash of the opened workbook
TempWkBk.Windows(1).Visible = False 'Only necessary if you also need to prevent
'the user from manually accessing the opened
'workbook before it is closed.
'Operate on the new workbook, which is not visible to the user, then close it...
Open the workbook as hidden and then set it as "saved" so that users are not prompted when they close out.
Dim w As Workbooks
Private Sub Workbook_Open()
Application.ScreenUpdating = False
Set w = Workbooks
w.Open Filename:="\\server\PriceList.xlsx", UpdateLinks:=False, ReadOnly:=True 'this is the data file were going to be opening
ActiveWindow.Visible = False
ThisWorkbook.Activate
Application.ScreenUpdating = True
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
w.Item(2).Saved = True 'this will suppress the safe prompt for the data file only
End Sub
This is somewhat derivative of the answer posted by Ashok.
By doing it this way though you will not get prompted to save changes back to the Excel file your reading from. This is great if the Excel file your reading from is intended as a data source for validation. For example if the workbook contains product names and price data it can be hidden and you can show an Excel file that represents an invoice with drop downs for product that validates from that price list.
You can then store the price list on a shared location on a network somewhere and make it read-only.
Open them from a new instance of Excel.
Sub Test()
Dim xl As Excel.Application
Set xl = CreateObject("Excel.Application")
Dim w As Workbook
Set w = xl.Workbooks.Add()
MsgBox "Not visible yet..."
xl.Visible = True
w.Close False
Set xl = Nothing
End Sub
You need to remember to clean up after you're done.
In excel, hide the workbooks, and save them as hidden. When your app loads them they will not be shown.
Edit: upon re-reading, it became clear that these workbooks are not part of your application. Such a solution would be inappropriate for user workbooks.