VBA Worksheets.Copy method changes comma style behaviour - vba

I used the following code to copy two sheets from my workbook to another file:
Worksheets(Array("One", "Two")).Copy
With ActiveWorkbook
.SaveAs Filename:=dir & "New_" & d & ".xlsx", FileFormat:=51
.Close SaveChanges:=False
End With
But it seems to change the way negative numbers are treated by comma style. In the original workbook, pressing the physical "Comma style" button would make a number look like -734,343.54 (with the minus sign at the far left). While in the new file it gives it parentheses, i.e. (734,343.54).
Setting the style as "Accounting" gives the same results for both workbooks, that is with the minus sign, except it includes the currency, which I do not need. How could I make sure that comma style does not change it's behaviour?
Update (more understandable code):
Sub test()
Worksheets(Array("Sheet1")).Copy
With ActiveWorkbook
.SaveAs Filename:="New" & ".xlsx", FileFormat:=51
.Close SaveChanges:=False
End With
End Sub

Adding Local:=True as a parameter to .SaveAs did the trick. From what I found:
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/workbook-saveas-method-excel
True saves files against the language of Microsoft Excel (including control panel settings). False (default) saves files against the language of Visual Basic for Applications (VBA) (which is typically US English unless the VBA project where Workbooks.Open is run from is an old internationalized XL5/95 VBA project).
It seems that this mostly applies to users who don't use English as the main language for Excel.

Related

VBA Overwrite Addin Workbook

So I have done some research but I can't get the feature I am looking for to work.
I am deploying a workbook to a lot of people on a network. I have an add-in on a network drive that all of the workbooks reference to. It works great when running the macros, no problem at all. My issue is updating the macros when people have one of the workbooks open. People leave things open for days sometimes, I know, cause I do the same thing sometimes.
I found this link, with the code below but I can't get it to work.
https://www.excelguru.ca/content.php?152-Deploying-Add-ins-in-a-Network-Environment
The macro saves it as a .xlsm or a macro enabled workbook. It won't save it as a .xla
Sub DeployAddIn()
'Author : Ken Puls (www.excelguru.ca)
'Macro Purpose: To deploy finished/updated add-in to a network
' location as a read only file
Dim strAddinDevelopmentPath As String
Dim strAddinPublicPath As String
'Set development and public paths
strAddinDevelopmentPath = ThisWorkbook.Path & Application.PathSeparator
strAddinPublicPath = "F:\Addins" & Application.PathSeparator
'Turn off alert regarding overwriting existing files
Application.DisplayAlerts = False
'Save the add-in
With ThisWorkbook
'Save to ensure work is okay in case of a crash
.Save
'Save read only copy to the network (remove read only property
'save the file and reapply the read only status)
On Error Resume Next
SetAttr strAddinPublicPath & .Name, vbNormal
On Error Goto 0
.SaveCopyAs Filename:=strAddinPublicPath & .Name
SetAttr strAddinPublicPath & .Name, vbReadOnly
End With
'Resume alerts
Application.DisplayAlerts = True
End Sub
I've tried doing
.SaveAs FileFormat:=xlAddIn
Or
.`SaveAs FileFormat:=18`
Niether of those work. SaveCopyAs doesn't have a fileformat option.
Any suggestions or any other methods that might work?
You keep a copy of the XLAM on your local machine that you update, and then when you are ready to deploy it, you copy the XLAM to the server. Everyone else runs off a copy that is on the server (you dont want them to copy it to their local machine, btw) - The key is that when you copy it to the server, you have to set it to read-only in the file properties. You have to do that every time you copy it. Then you can overwrite it at any time.
Comment if you have any questions - I do this every day for work.

Disabling macros from other Excel sheets

I'm working on a few VBA macros in Excel for a project. Is there a way to ensure that VBA macros don't launch from other Excel workbooks when you are opening them through a macro?
For example, let's say I have a macro inside one workbook to open some other Excel file:
Sheets("Sheet1").Select
PathName = Range("D3").Value
Filename = Range("D4").Value
TabName = Range("D5").Value
ControlFile = ActiveWorkbook.Name
Workbooks.Open Filename:=PathName &; Filename
What I've usually done is include a Application.EnableEvents = False to the subroutine to ensure that I'm not triggering code upon opening the other workbooks. This is also the methodology suggested by this prior SO post.
But two questions come to mind:
Is this "secure"? Are there other ways that users could write their own macros that execute on my active application even if I disable events?
Are there other workarounds besides fully disabling events? This seems somewhat limiting and almost "throwing the baby out with the bathwater".
This seems to open the file without the macros and it's read only.
When testing this, I can't even see the macro module in VBA editor for the opened file..
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Workbooks.Open Filename:=strFilepath & strFilename, ReadOnly:=True
Application.AutomationSecurity = msoAutomationSecurityByUI

Excel VBA code is causing my worksheets to appear as jargon

I currently am using a VBA macro that I found here on stack over flow. The problem is when I run it it saves all the data into a separate excel sheet but when i open it it appears as "jargon" in other words unreadable type. This is the "Save code"
'Save the new workbook, and close it
wb.SaveAs ThisWorkbook.Path & "\test" & WorkbookCounter
wb.Close
The way I am currently running the code is that it separates my excel sheets into different spread sheets by rows of 250. Everything works but when I open the saved documents it says that this file format is unacceptable to Excel. Then I try importing it and I get an error. Here is a snap shot of the way it appears in my screen. Also here is the file name: built.list\test.xls39
Your workbook counter always ends in a number, Windows and Excel use the file extension to determine file-type, so an '.xls39' file is unrecognisable. Try:
wb.SaveAs _
Filename:=ThisWorkbook.Path & "\test" & WorkbookCounter & ".xls" _
FileFormat:=XlFileFormat.xlExcel8
'Use xlOpenXMLWorkbook for the .xlsx format
(Use space followed by underscore to separate lines in VBA)
Or make sure WorkbookCounter ends in .xls and not a number.
(Edit: For other formats, please look in the References dialog in Excel VBA Editor)

Blank worksheets opened up every time Excel starts - accidentally created after splitting Spreadsheet using VBA code

I need a bit of help with Xcel 2010.
I have a spreadsheet budget workbook in Xcel 2010 that had 6 tabs of worksheets. I needed to make a copy of just one of those worksheets to pass on to someone who was not allowed to see the other worksheets.
I used this VBA code shown below to split up the workbook and it worked just fine. But, since doing so, now every time I open up any Xcel file I get three blank worksheets that open up at the same time and they are labeled as Tabelle1.xls, Tabelle2.xls and Tabelle3.xls.
I thought that using another VBA code (see below the other code) to delete the module would take care of that but it did not. Now there is no code/module at all if I open up Visual Basic but I still get three blank worksheets that open up separately from whatever Xcel file I open up. The three blank worksheets all have the .xls file extension but the version of MS Office I have uses .xlsx.
Other info: I am using Windows 7, this is my work computer and do not know anything about VBA coding myself. I was just looking for a quick fix by Googling and got myself in trouble.
The code to split up the Workbook
Sub Splitbook()
MyPath = ThisWorkbook.Path
For Each sht In ThisWorkbook.Sheets
sht.Copy
ActiveSheet.Cells.Copy
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats
ActiveWorkbook.SaveAs _
Filename:=MyPath & "\" & sht.Name & ".xls"
ActiveWorkbook.Close savechanges:=False
Next sht
End Sub
The code I used to delete the module:
Sub DeleteModule()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents("Module1")
VBProj.VBComponents.Remove VBComp
End Sub
SectionBreak
Your symptoms are indicative of a workbook being in the XLSTART folder (an 'autorun' folder). The reason for the names being "Tabelle" are that the source of this workbook was likely a German locale.
Any workbook in this folder is opened whenever the Excel application starts up. It is a folder typically used to place your personal macro workbooks so macros within are automatically available when working on different workbooks.
In your case, this appears unintentional. Check the folder at, typically:
Win7/8: C:\Users\[Username]\AppData\Roaming\Microsoft\Excel\XLSTART
WinXP: C:\Documents and Settings\[Username]\Application Data\Microsoft\Excel\XLStart
and clear out any files you were not expecting there.
I refer you to http://office.microsoft.com/en-gb/excel-help/customize-how-excel-starts-HP010197489.aspx for more details over how you can customise the templates and workbooks Excel uses to achieve helpful results.

Using vba to copy the contents of a word document into another word document

I haven't used VB for years, so please forgive me if this turns out to be obvious. I'm trying to write a word vba macro for use in a template which will display a userform and then import the contents of fileA.docx, fileB.docx, or fileC.docx depending on the userform. (After that I'm going to use bookmarks to fill in some form data, I don't know if that's relevant). Files A, B, and C will contain text with some basic formatting such as lists, but nothing fancy.
The solutions I've seen online can copy the contents of file to a new file, but ideally I would like to import the entirety of one of those files into the new, currently unnamed file that I'm getting from the template. I think where I'm running into problems is with switching the selection to one of those files, and then back to the new unnamed document, though I could use a hand to make sure I'm copying correctly as well.
Update: I was making things too hard, though the answers here got me pointed in the right direction (thanks!). In the end I just did
ThisDocument.Activate
Selection.InsertFile("fileA")
which gives me the raw dump of everything that I wanted.
Using commands such as these you can switch between which Document you're using and copy and paste elements:
ThisDocument.Activate 'Sets the main document active
Documents("Name.doc").Activate 'Activates another document
You can insert, copy and paste things in and out of documents using copy commands.
ThisDocument.Range.InsertAfter("String") 'Insert text
Selection.WholeStory 'Select whole document
Selection.Expand wdParagraph 'Expands your selection to current paragraph
Selection.Copy 'Copy your selection
Documents("name.doc").Activate 'Activate the other document
Selection.EndKey wdStory 'Move to end of document
Selection.PasteAndFormat wdPasteDefault 'Pastes in the content
You can then go and format such, or copy and paste them with original formatting from before.
Here is a significant improvement (I think) you will want to incorporate because it:
does not use the clipboard and thus does not make your macro vulnerable to the user changing the contents of the clipboard while your macro is running
does not use a file and thus greatly improve the speed by eliminating I/O and eliminates the potential of having to deal with file system security/permissions, etc. Please do not use .InsertFile() if you are looping through documents you will slow yourself down. Use it once, at the end -only if you have to. The example below shows how to accomplish the same result without using .InsertFile()
The idea is to transfer some portion of text found in 1 source document, to a destination document that is different than the source, and keep the source formatting.
To accomplish the above (skipping the code to open documents):
For Each oTable In oDoc_Source
'the above could have been anything that returns a Range object
'such as: ActiveDocument.Content.Find.Execute ....
'...
'logic here to identify the table, or text, you are looking for
'...
'I can't believe the MS Dev Center folks could only think
'of .InsertFile(), which is the last resort I would go for,
'especially if your code runs on a web server [concurrent web requests]!
'SAFEST
'(no user interference on clipboard possible, no need to deal with file i/o and permissions)
'you need a reference to Document.Content,
'as the act of obtaining a reference "un-collapses" the range, so the below 3 lines must be in that order.
Set oRange = oDoc_DestinationDoc.Content
oRange.Collapse Direction:=wdCollapseEnd
oRange.FormattedText = oTable.Range
'BRUTE, AND PRONE TO RANDOM ERRORS AND HANGS DUE TO USER INTERFERENCE WITH CLIPBOARD
'find a way to implement WIHTOUT using the CLIPBOARD altogether to copy the below range object
'it will be easier for PC users to use the clipboard while the macro runs
'and it will probably be safer for the output of this macro to remain uncorrupted
'oTable.Range.Copy
'Set oRange = oDoc_DestinationDoc.Content
'oRange.Collapse Direction:=wdCollapseEnd
'oRange.Paste
'THE BELOW DOES NOT WORK
' '1) - cannot add a range from another document
' 'adds only text, not the formats and not the table layout
' oTable.Range.TextRetrievalMode.IncludeFieldCodes = True
' oTable.Range.TextRetrievalMode.IncludeHiddenText = True
' oDoc_DestinationDoc.Content.InsertAfter oTable.Range
'
' '2) - cannot add a range from another document
' oDoc_DestinationDoc.Content.Tables.Add oTable.Range, iRowMax, iColMax
'
' '3) - only puts in plain text, and it replaces the range without the .Collapse call
' oDoc_DestinationDoc.Content.Text = oTable.Range
Record a macro...
start in the source document
press ctrl-a to select everything
press ctrl-c to copy it to the clipboard
switch to the target document
press ctrl-v to paste into the document
stop recording
or (assuming word 2007 or later)
start in the target document with the source document closed
on the ribbon click insert > object > Text from file...
navigate to the source document
click the insert button
stop recording
I prefer the second version so I should have put it first
I was doing the same thing, tried to select the other document, copy and paste. But it didn't worked (I received an error probably because some other application was using the clipboard, but I am not sure.). So I did a little search and found the perfect solution on Microsoft Dev Center.
https://msdn.microsoft.com/en-us/vba/word-vba/articles/selection-insertfile-method-word
Selection.Collapse Direction:=wdCollapseEnd
Selection.InsertFile FileName:="C:\TEST.DOC"
'set current doc name and path
Dim docName As String: docName = ActiveDocument.name
Dim filepath As String: filepath = ActiveDocument.Path
'create a new file
Documents.Add
'get the path of a current file
ChangeFileOpenDirectory filepath
'insert content of current file to newly created doc
Selection.InsertFile _
FileName:=docName, _
Range:="", _
ConfirmConversions:=False, _
Link:=False, _
Attachment:=False
'open prompt to save a new file
With Dialogs(wdDialogFileSaveAs)
.name = docName & "-copy"
.Show
End With