PATRI0T Пользователь Сообщений: 5 |
#1 05.10.2017 11:28:30 Добрый день. Что делаю:
Этой процедурой удаляю макросы (пытаюсь)
В результате Вопрос. Прикрепленные файлы
|
||||
_Igor_61 Пользователь Сообщений: 3007 |
Можно. Побаловался макрорекордером и у меня получилось |
PATRI0T Пользователь Сообщений: 5 |
#3 06.10.2017 08:17:17 Спасибо за ответ А зачем это?
|
||
Александр П. Пользователь Сообщений: 1147 |
#4 06.10.2017 08:53:07 PATRI0T, Код ниже удаляет весь код во всех модулях активной книги.
|
||
_Igor_61 Пользователь Сообщений: 3007 |
#5 06.10.2017 09:07:38
Покажите Ваш файл с кодом, который не работает. Смею предположить, что Вы что-то не так или не туда вставили или что-то не так сделали, а так же невнимательно посмотрели код, иначе не возникло бы вопроса:[QUOTE]PATRI0T написал: А зачем это? Kill Addr & «Файл без макросов 2007.xlsx[/CODE] |
||
_Igor_61 Пользователь Сообщений: 3007 |
Александр, здравствуйте! Но тогда пользователю нужно лезть в параметры, ставить доверенный доступ и перезапускать приложение, что для пользователя, думаю не очень удобно. Поэтому по-моему проще это все сделать просто пересохранением файлов, а потом лишний файл удалить. ИМХО, конечно |
_Igor_61, ну так, наше дело предложить вариант . Изменено: Александр П. — 06.10.2017 10:19:58 |
|
sokol92 Пользователь Сообщений: 4445 |
Уважаемый PATRI0T, в приложенном к сообщению файле макросов нет, зато есть два «битых» имени книги. Удалите их через «Диспетчер имен» и проблема с открытием должна уйти. |
_Igor_61 Пользователь Сообщений: 3007 |
#9 07.10.2017 00:34:38
Да, если это так, то не удивительно, что у него мой макрос не работает, если он его в xls помещает. Но почему-то он про этот момент молчит. А я решил, что у него изначальный файл в xlsm, глядя на картинку |
||
LAD Пользователь Сообщений: 22 |
Вы копируете лист со всеми потрохами. Копируйте только то, что Вам нужно. Сделайте новый лист и на него скопируйте диапазон ячеек. Изменено: LAD — 07.10.2017 04:58:21 |
RAN Пользователь Сообщений: 7091 |
#11 07.10.2017 09:48:49
_Igor_61, Вставьте это в модуль копируемого листа, и вау съедят мыши.
Изменено: RAN — 07.10.2017 10:51:58 |
||||
_Igor_61 Пользователь Сообщений: 3007 |
RAN, не, не съедят, еще больше «ВАУ»! |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
$ в имени переменной — это тип (аналог as String). Вот табличка соответствий: // xlCSVWindows = 23; // основные константы 2007 // 57 = PDF |
_Igor_61 Пользователь Сообщений: 3007 |
Блин, как же я люблю этот форум! Каждый раз какое-то «ВАУ» для себя нахожу! Юрий М, спасибо большое! Сохранил Ваши пояснения, они очень пригодятся в дальнейшем. Не знал, что части кода можно цифрами задавать (хотя, нет, пример уже знаю — в MsgBox 64, 32, 48), это, видимо, что-то подобное, если правильно понимаю. Т.е. вместо «xlOpenXMLWorkbook (without macro’s in 2007-2010, xlsx) » пишем «51» и выполняется это действие, так? И я так понимаю, что RAN своим кодом вносит изменения в XML? Дальше — вообще не понимаю — ведь если открыть файл через WinRAR, там же куча папок и файлов XML, т.е. в данном случае через «51» производятся манипуляции с конкретным XML файлом, «51» его находит и выполняет свою задачу? |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
XML тут нет ) Просто заменяем длинную строку числом ) |
_Igor_61 Пользователь Сообщений: 3007 |
xlOpenXMLWorkbook — тогда это просто указание на книгу xlsx 2007-2010, этим кодом ее открываем? |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
Нет, открываем по имени, а это указание ТИПА файла — книга без макросов. |
_Igor_61 Пользователь Сообщений: 3007 |
А, кажется понял: ActiveWorkbook.SaveAs sfName1, 51 — сохраняем активную книгу с заданным именем (sfName1) в xlsx (xlOpenXMLWorkbook (without macro’s in 2007-2010, xlsx) . И равнозначно — можно записать текстом «xlOpenXMLWorkbook (without macro’s in 2007-2010, xlsx», а можно «51». Я правильно понимаю? |
Николай Пользователь Сообщений: 229 |
RAN, ваш макрос в личную книгу макросов. Что нужно изменить что бы макрос заработал из личной книги макросов. Из листа текущей книги отрабатывает корректно. Изменено: Николай — 07.10.2017 19:42:37 |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
|
_Igor_61 Пользователь Сообщений: 3007 |
|
RAN Пользователь Сообщений: 7091 |
sfName1 =
ActiveWorkbook.FullName Изменено: RAN — 07.10.2017 20:30:39 |
RAN Пользователь Сообщений: 7091 |
_Igor_61, |
Николай Пользователь Сообщений: 229 |
Кнопка цитирования не для ответа [МОДЕРАТОР] sfName1 = ActiveWorkbook.FullName |
Николай Пользователь Сообщений: 229 |
#25 07.10.2017 21:46:53 На тестовой книге.
И скрин ошибки. Прикрепленные файлы
|
||
Николай Пользователь Сообщений: 229 |
#26 07.10.2017 21:49:24 Опа.
Решило проблему. |
||
Николай Пользователь Сообщений: 229 |
#27 08.10.2017 09:51:08 Вот как стал выглядеть код в итоге.
Огромная благодарность RAN, за его код сохранения файлов. Изменено: Николай — 08.10.2017 12:38:36 |
||
LAD Пользователь Сообщений: 22 |
#28 08.10.2017 14:57:17 Не думал, что можно так сильно извратить. |
Dear Friends,
This is a very simple yet powerful Excel VBA tip for you. Many a time before sending your workbook with Excel VBA Macro code in it, you want to save your workbook without any VBA code in it.
Therefore here in this article, I will show you – how to save your Excel Workbook without excel macro in it.
This can be done manually as well as using Excel VBA.
At the end of this article, I have a usage example of this VBA method. You can also download a FREE Excel Workbook for you to understand and play around.
Method 1: Manual : Save a Copy of Excel workbook without Macro in it manually
Method 2: VBA: Save a Copy of Excel workbook without Macro using Excel VBA
Download an Excel Workbook to play around [FREE DOWNLOAD]
Manual Method: Save Workbook without Excel Macro
Follow the below steps to save a copy of your workbook as Excel Macro FREE. There will be no excel Macro code in the copy saved.
Step 1:
Go to File Option and Click on Save AS of your xlsm file as shown in the below picture:
Excel Workbook with Excel Macro in it
Step 2:
Now save your workbook as xlsx and not as xlsm as shown in the below picture
VBA To SaveAs xlsx
Step 3:
On clicking on save, you receive following confirmation popup, once you click on “Yes” then your excel workbook will be saved without Excel Macro code.
Confirmation Popup – Save Excel without Excel Macro Code
Step 4:
Now once you open your .xlsx workbook, you would not see any of the excel macro code as shown in below picture:
Excel Workbook Without Macro
VBA Method: Save Workbook without Excel Macro using Excel VBA
Now as you have seen how to achieve this manually, I will show you how you can achieve this by using Excel VBA.
Following VBA statement will be able to save your Workbook with Excel Workbook as a Workbook without any Excel VBA code in it.
ThisWorkbook.SaveAs Filename:="C:...abc.xlsx", FileFormat:=xlOpenXMLWorkbook
While executing the above, VBA statement, you will receive the same confirmation popup as shown above – which you get while saving your .xlsm workbook as .xlsx.
This can be annoying in an automated process. To ignore this popup in Excel VBA code, you simply use Application.DisplayAlerts to false before executing the above statement.
Save Excel workbook as Excel Macro FREE Workbook without confirmation Popup
Refer the below VBA code to save your Excel workbook without saving any VBA code in it.
Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:="C:...abc.xlsx", FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = True
Example of usage of above Code
You have an excel workbook which has Excel VBA code inside it to generate a report or to perform any automated task. While sending the copy of that excel workbook, you do not want to send all the code, etc. inside it. In such case you can use above code in order to save the workbook as macro free before attaching to the email.
If you want to know more about it, you can read this article here.
Send current workbook as Macro FREE Workbook as an Attachment in email
Using below code, you can send your current workbook without any VBA code in it which already has VBA codes in it. This is one of the best usage of saving a workbook as Excel Macro FREE Workbook.
Before sending your workbook as an attachment in email, you do not want to share the code along-with the workbook, then this piece of code will do the magic for you.
Sub Email_CurrentWorkBook()
'Do not forget to change the email ID
'before running this code
Dim OlApp As Object
Dim NewMail As Object
Dim TempFilePath As String
Dim fileName As String
Dim originalWB As Workbook
Dim tempWB As Workbook
Dim tempXLSXPath As String
Dim tempXLSMPath As String
Set originalWB = ThisWorkbook
With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
' Save your workbook in your temp folder of your system
' below code gets the full path of the temporary folder
' in your system
TempFilePath = Environ$("temp") & ""
fileName = VBA.Left(originalWB.Name, (InStrRev(originalWB.Name, ".", -1, vbTextCompare) - 1))
fileName = fileName & "-" & Format(Now, "dd-mmm-yy h-mm-ss")
tempXLSMPath = (TempFilePath & fileName & ".xlsm") ' with macro - as is
tempXLSXPath = (TempFilePath & fileName & ".xlsx") ' without macro
' first an as is copy of this workbook is created
' and saved as with Macro in it [.xlsm] format
originalWB.SaveCopyAs (tempXLSMPath)
' Now open this copy of the current workbook
' and saveAs a Macro FREE Workbook [.xlsx] format
Set tempWB = Workbooks.Open(tempXLSMPath)
With tempWB
.SaveAs fileName:=tempXLSXPath, FileFormat:=xlOpenXMLWorkbook
.Close savechanges:=False
End With
' Now open a new mail
Set OlApp = CreateObject("Outlook.Application")
Set NewMail = OlApp.CreateItem(0)
On Error Resume Next
With NewMail
.To = "abc@xyz.com"
.CC = "abc@xyz.com"
.BCC = "abc@xyz.com"
.Subject = "Type your Subject here"
.Body = "Type the Body of your mail"
.Attachments.Add tempXLSXPath ' attach .xlsx file
.Send 'or use .Display to show you the email before sending it.
End With
On Error GoTo 0
' Since mail has been sent with the attachment
' Now delete both the temp files
' .xlsx and .xlsm
Kill tempXLSMPath
Kill tempXLSXPath
'set nothing to the objects created
Set NewMail = Nothing
Set OlApp = Nothing
Set originalWB = Nothing
Set tempWB = Nothing
'Now set the application properties back to true
With Application
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
End With
End Sub
*************IMPORTANT***********:
In the above code, as you can see, first I have created an exact copy of the current workbook with Macro and then I have saved that copy as a Macro FREE workbook. Strange?? Isn’t it?? Why did not I directly used SaveAs statement to save the current workbook as Macro FREE workbook and then attach it to the email and send?
There is a valid reason for doing so… Before I explain the reason, I would like you to read these two main differences between these two methods…
Difference between SaveAs and SaveCopyAs in Excel VBA
Following are the two main differences between these two methods in Excel VBA…
Difference No: 1 :
After running the SaveAs command, new workbook becomes the current Workbook [in VBA terms – ThisWorkbook]. In other words, after running the SaveAs command, your original workbook will no longer remain opened and accessible [unless you open the original workbook again by providing the Workbooks.Open command].
While SaveCopyAs does it exactly opposite. Here original workbook remains open and copy is made as-it-is with the given file name and path.
This is the reason… why I could not directly use this SaveAs method to save a macro free copy of the current workbook where actually my code is running. So as soon as Save As command is run, then in the current workbook there is no macro any more and code will stop running there and further statements will not be executed any more.
Difference No: 2 :
Using SaveAs you can change many things around your Excel Workbook.. like
1. Secure it by providing a password
2. Change the FileName, FilePath, FileFormat, FileType etc.
any more…
While using SaveCopyAs, all you can do is just change the FileName or FilePath or both. Other than this, you can not make any changes in the workbook. It is simply an AS-IS copy of your workbook.
This is the reason… why I could not just use SaveCopyAs method. By using this method, I can not change for FileFormat of the Workbook as Macro FREE (.xlsx).
Now you understand, why a combination of these two methods was required in order to achieve this scenario of sending a Macro FREE copy of current Excel Workbook as an attachment in an email.
-
#2
have a read here > https://www.rondebruin.nl/win/s5/win001.htm bearing in mind you want to change the workbook to one without macros that is currently running a macro, or you could use the routine to just save the woeksheet itself as the xlsx
-
#3
Dear Mole999,
Thanks very much for your prompt and kind response to my Post.
I must confess that my knowledge of vba is still very basic. I got through to the link that you provided.
Unfortunately, due to my very basic knowledge, the options provided got me confused, hence I ask for your further kind help or that of any other forum member.
A kind friend provided me with the code in my Post #1 above. The code works OK to use it for saving as a PDF. However, there is need now to discontinue saving as PDF but as a normal Excel file without macros. I need it to complete a task that I currently have.
I should therefore be grateful if the code in my Post #1 can be tweaked or adjusted to meet that need. If saving the Excel worksheet as a normal Excel file (without macros) would require a code that is completely different altogether from that which I have shown in my Post #1 , I’d appreciate help with that, please. I wish I knew which of the options listed in the rondebruin link to choose that would meet my need.
I look forward to further help with this, please.
Thanks.
Kenny
Last edited: Dec 24, 2017
Fluff
MrExcel MVP, Moderator
-
#4
Untested, but try
Code:
' 1 Newly created file is saved as a PDF file
Path = "C:Copy Invoices"
ActiveWorkbook.SaveAs FileName:=Path & "" & sNewWorkbookName & " - " & [G5], FileFormat:=51
-
#5
Thanks Fluff for your kindness and for your very helpful code.
Although it saved the worksheet as a macro-free Excel file, there are two problems, about which I need your help:
1. The main Invoice Sheet has the following command buttons — ‘Save & Clear’; ‘Exit‘. Although the main Invoice form and details cover A1 to N52, the above command buttons reside in columns O to R.
And when I click on the ‘Save & Clear’ command button, and it eventually saves the worksheet, I find that the saved copy contains those two command buttons.
I would like it to save the worksheet, but without the command buttons appearing on the saved copies, please.
2. When I click on the ‘Save & Clear’ command button, I get a message box with the following message:
‘The following features cannot be saved in macro-free workbook: .VB Project.
To save a file with these features, click No and then choose a macro-enabled file type in the file type list.
To continue saving as a macro-free workbook, click Yes.’
I have to click Yes for it to save as macro-free. Please is there any adjustment that can be made to your code to prevent above message and get it to save straightaway the copy as a macro-free fille?
Apart from these two issues, every thing else is fine, and I am grateful to you for your help.
Thanks very much.
Kenny
Fluff
MrExcel MVP, Moderator
-
#6
Try
Code:
Dim Shp As Shape
Dim Pth As String
For Each Shp In ActiveSheet.Shapes
Shp.Delete
Next Shp
Pth = "C:Copy Invoices"
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=Pth & "" & sNewWorkbookName & " - " & [G5], FileFormat:=51
Application.DisplayAlerts = True
-
#7
Dear Fluff,
Thanks for your continued support.
The corrected code (ref your post #6 ) almost did the job except for some minor issue.
Meanwhile, I am sorry that I did not inform you that the body of the Invoice Sheet contains some Option buttons which have to be selected while completing the Invoice. These option buttons are required as part of the Invoice.
Therefore, what happens is that the following line of your code deletes all the ‘command buttons’ includiang the ‘option buttons’ in the body of the Invoice:
Code:
For Each Shp In ActiveSheet.Shapes
Shp.Delete
Next Shp
In the course of saving the worksheet as a macro-free file, I would like the code to exclude/delete the command buttons, but not the option buttons in the body of the Invoice. I believe that the word ‘Shapes’ in the code covers both the command buttons and option buttons. Please, is there anything that can be done to delete only the command buttons and not the option buttons in the body of the Invoice?
I have no doubt that this final tweak will completely solve my problem.
Again, thanks for all your help.
Kenny
Last edited: Dec 25, 2017
Fluff
MrExcel MVP, Moderator
-
#8
How about
Code:
Private Sub CommandButton1_Click()
'Ron de Bruin https://www.rondebruin.nl/win/s4/win002.htm
Dim obj As OLEObject
Dim Pth As String
For Each obj In ActiveSheet.OLEObjects
If TypeOf obj.Object Is MSForms.CommandButton Then
obj.Delete
End If
Next
Pth = "C:Copy Invoices"
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=Pth & "" & sNewWorkbookName & " - " & [G5], FileFormat:=51
Application.DisplayAlerts = True
End Sub
-
#9
Dear Fluff,
I am very sorry for bothering you this much with this problem which appears to be somewhat knotty. I have tried your code but can’t seem to get it it to work. The code does not get rid of, from the saved copies, the buttons that control the macros.
I must add that your code, in your Post #6 above as follows:
Code:
Dim Shp As Shape
Dim Pth As String
For Each Shp In ActiveSheet.Shapes
Shp.Delete
Next Shp
which refers to the buttons as ‘shapes’ successfully got rid of the shapes which control the macros, and which serve, for me, as command buttons. The only unfortunate thing is that in doing so, it also got rid of the option buttons, which should be allowed to remain.
I created those ‘command buttons’ using the ‘Insert Shapes’ feature in my Excel 2007. The shapes look more elegant than either the ‘Form’ or ‘ActiveX’ command buttons.
Unfortunately, your most recent code (Post #8 ) does not delete any of the command buttons (whether created with shapes or with Form or ActiveX) from the saved copies.
As I searched some other forum, I came across a thread by someone who had a somewhat similar issue — although not completely the same as mine. The member indicated that he solved his own problem with the following vba code:
Code:
[B]'Delete the command button in new workbook[/B]
[B]With ActiveSheet[/B]
[B] .Shapes("CBONew").Delete[/B]
[B] .Shapes("CBOSave").Delete[/B]
[B]End With[/B]
I assume that the two buttons he has that control the macros are named ‘New’ and ‘Save’, respectively.
The two shapes that I have (which control macros, and which I want deleted from the saved copies of the Invoice) are named ‘SAVE’ and ‘EXIT’, respectively.
I tried to replicate his code — inserting the names of my own two shapes. But I keep getting ‘Runtime Errors’.
I wish to retain the two beautiful shapes and having them serve as command buttons, and wish that there is a way your code (Post #6 ) could be tweaked to do the trick for me — or indeed any other code that can do it.
The whole thing is not only frustrating me, but I seem to be letting you share in my frustration — even at Christmas! Please, I sincerely apologize for the bother.
I remain eternally grateful to you for your continued help.
Kenny
Last edited: Dec 25, 2017
Fluff
MrExcel MVP, Moderator
-
#10
Try
Code:
Sub RemoveShapes()
Dim Shp As Shape
Dim Pth As String
For Each Shp In ActiveSheet.Shapes
If Not (Shp.Type = msoOLEControlObject Or Shp.Type = msoFormControl) Then Shp.Delete
Next Shp
Pth = "C:Copy Invoices"
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=Pth & "" & sNewWorkbookName & " - " & [G5], FileFormat:=51
Application.DisplayAlerts = True
End Sub
You will need to set a reference.
In the VBE select tools > References > Microsoft Office xx.0 Object Library (make sure you check the box, rather than just select the line) > OK
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS
Contact US
Thanks. We have received your request and will respond promptly.
Log In
Come Join Us!
Are you a
Computer / IT professional?
Join Tek-Tips Forums!
- Talk With Other Members
- Be Notified Of Responses
To Your Posts - Keyword Search
- One-Click Access To Your
Favorite Forums - Automated Signatures
On Your Posts - Best Of All, It’s Free!
*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.
Posting Guidelines
Promoting, selling, recruiting, coursework and thesis posting is forbidden.
Students Click Here
Save Excel without macros?Save Excel without macros?(OP) 24 Aug 04 11:26 I’d like to save a workbook via vba without saving the macros using the following code:- ActiveWorkbook.SaveAs FileName:=Name, FileFormat:= _ If this is not possible, is it possible to disable the macro’s when the new saved document is opened? CodMan Red Flag SubmittedThank you for helping keep Tek-Tips Forums free from inappropriate posts. |
Join Tek-Tips® Today!
Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.
Here’s Why Members Love Tek-Tips Forums:
- Talk To Other Members
- Notification Of Responses To Questions
- Favorite Forums One Click Access
- Keyword Search Of All Posts, And More…
Register now while it’s still free!
Already a member? Close this window and log in.
Join Us Close
Сохранить файл без макросов |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |