I have some code which keeps causing an
Error 70: Permission Denied
in my VBA code. I can’t work out why, because I know that the worksheet is unprotected and that I can make changes to it. The code in question is
sh.Name = "square"
It attempts to rename a shape that has been copied from another sheet and pasted into the sheet — there are no other shapes in the sheet with that name, because prior to these code I have already deleted all shapes with that name.
Any suggestion as to what might cause this permissions error?
lfrandom
9932 gold badges9 silver badges31 bronze badges
asked Jun 4, 2009 at 6:51
1
Generally that one is caused by trying to use the same name twice. Try doing this instead:
Sub Example()
Dim lngIndx As Long
Dim ws As Excel.Worksheet
Dim shp As Excel.Shape
Set ws = Excel.ActiveSheet
Set shp = ws.Shapes.AddShape(msoShapeOval, 174#, 94.5, 207#, 191.25)
If NameUsed(ws, "Foo") Then
lngIndx = 2
Do While NameUsed(ws, "Foo" & CStr(lngIndx))
lngIndx = lngIndx + 1
Loop
shp.name = "Foo" & CStr(lngIndx)
Else
shp.name = "Foo"
End If
End Sub
Private Function NameUsed(ByVal parent As Excel.Worksheet, ByVal name As String) As Boolean
Dim shp As Excel.Shape
Dim blnRtnVal As Boolean
name = LCase$(name)
For Each shp In parent.Shapes
If LCase$(shp.name) = name Then
blnRtnVal = True
Exit For
End If
Next
NameUsed = blnRtnVal
End Function
answered Jun 4, 2009 at 7:18
OorangOorang
6,6201 gold badge35 silver badges52 bronze badges
4
Clean as you go. Set objects to nothing, strings to nullstring after using them and don’t use the same names between functions and subroutines.
answered Apr 10, 2012 at 9:58
«Permission Denied» is not for a protected worksheet but for wrong access to a property or variable.
I believe that «sh» is null at the point you are trying to access it and set its «Name» property. try to see if you initialized it correctly before setting its properties.
answered Jun 4, 2009 at 7:03
David SalzerDavid Salzer
8721 gold badge7 silver badges24 bronze badges
1
There are several answers here on StackOverflow about this VB Error. Each answer or situation is unique in reality — although each existing answer states a different potential root cause (file permissions, folder permissions, name reuse, ranges, etc).
I would recommend narrowing down the root-cause by double clicking on the side of the stating function/code in order to mark a breakpoinnt (looks like a red dot) (Alternatively, you can right click on the line of the code — Select the Toggle
and then Breakpoint
).
Next, run your code, and it will stop in your breakpoint. You can then Step-Into/Over/Out your code and essentially find the line of code that is responsible for throwing your error code. (Step Into is F8
, Step over is Shift+F8
((Go To the Debug
top menu to see more options)))
Once you identified the responsible line of code — you can start looking further.
In my case scenario, I was using a protected variable name «Date» (look into variable names). Once I renamed it to something else, the problem was fixed.
answered Sep 12, 2019 at 13:53
KingsInnerSoulKingsInnerSoul
1,3433 gold badges20 silver badges48 bronze badges
Jktu Пользователь Сообщений: 4 |
#1 14.12.2021 12:30:55 При открытии файла 1 сохраняю его как файл 2.
Средствами windows я переместить или удалить файл тоже не могу. Она говорит «Нет доступа или файл уже используется».
|
||||
Юрий М Модератор Сообщений: 60735 Контакты см. в профиле |
Jktu, зачем Вы пишете через строку? зачем растягивать сообщение? Не нужно жать на Enter по несколько раз. |
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 14253 Профессиональная разработка приложений для MS Office |
#3 14.12.2021 13:14:36
не запускать код из той книги, которую хотите в архив запихнуть. Ведь в момент попытки закинуть в архив файл с кодом — код-то выполняется, а значит файл по сути «открыт». Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
Олег Пользователь Сообщений: 4 |
Не совсем так. Я сохранил файл с новым именем и фактически макрос крутиться в новом файле. Запускать код снаружи нет возможности. Изменено: Олег — 14.12.2021 13:30:42 |
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 14253 Профессиональная разработка приложений для MS Office |
#5 14.12.2021 14:05:48
это факт или Вы так думаете?
поясните так же — в какой момент Вы это пробуете делать? Это только с одним файлом или с любым файлом в этой папке? Изменено: Дмитрий(The_Prist) Щербаков — 14.12.2021 14:08:43 Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||
Олег Пользователь Сообщений: 4 |
#6 14.12.2021 14:44:16 Я так думал. Я предполагаю, что я ошибался и ищу где именно. Судя по тому, что я вижу название нового файла в дереве проекта, я сделал вывод, что код крутится в новом файле. Диспетчер задач показывает 2 процесса excel после saveas. Я пытался вызывать новый макрос на перемещение файла. Результат не поменялся. Поэтому спрашиваю совет у опытных. SaveCopyAs, тоже вариант, но не идеальный. 1) в итоге мне нужно иметь файл с новым именем в открытом состоянии. возможно стоит поискать переименование. Более полный код:
Надеюсь будут ещё идеи. Изменено: Олег — 14.12.2021 15:04:59 |
||
vikttur Пользователь Сообщений: 47199 |
Олег, зачем так рвать сообщение? |
Юрий М Модератор Сообщений: 60735 Контакты см. в профиле |
#8 14.12.2021 15:29:59
|
||
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 14253 Профессиональная разработка приложений для MS Office |
#9 14.12.2021 16:31:07 Может попробовать правильно перемещать?
Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
Евгений Смирнов Пользователь Сообщений: 539 |
#10 14.12.2021 16:54:40
Если исходный файл занят после оператора SaveAs мы в следующих строчках можем исходный файл( удалить, переместить, скопировать, переименовать)? Изменено: Евгений Смирнов — 14.12.2021 17:13:51 |
||
Евгений Смирнов, тут дело-то не простое…С одной стороны — файл не должен быть занят, если мы делаем Save As из меню. Там никаких отсылок на файл не остается. Но если делаем кодом — то какое-то время файл еще используется системой, т.к. его код был скомпилирован и он на текущий момент выполняется(да, там происходят процессы чуть иные, но будем считать так — файл все равно какое-то время после SaveAs используется). Сколько файл будет заблокирован зависит от того, где как и что происходит. Например, на локальном диске это будут скорее всего миллисекунды(опять же зависит от размера файла). После выполнения всех команд кода файл должен быть успешно перемещен в любом случае. А вот на сетевом(или что-то вроде виртуального рабочего стола) — это может занять и больше времени и вообще иначе отработать. Вроде код уже выполнил SaveAs и файл создался, и новый вроде как сейчас используется, а не исходный — но система все еще считает исходный файл занятым. И тут разные факторы могут повлиять на то, когда система его разблокирует и разблокирует ли вообще без презапуска Excel. Изменено: Дмитрий(The_Prist) Щербаков — 14.12.2021 17:25:55 Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
|
Евгений Смирнов Пользователь Сообщений: 539 |
#12 14.12.2021 17:28:25 Дмитрий(The_Prist) Щербаков
Спасибо за пояснения. Но тогда ещё как вариант после SaveAs можно задержку воткнуть.
|
||
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 14253 Профессиональная разработка приложений для MS Office |
#13 14.12.2021 17:37:58
а смысл? Сначала надо диагностировать, а потом костыли вешать. А если файл и без задержек нормально переместиться? Ждать 10 секунд? Не самая лучшая идея. К тому же метод Wait опять же может удерживать файл в процессах. Так же, если проблема в ОС — файл может вообще не получится освободить ни через 10 секунд, ни через полчаса. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
Евгений Смирнов Пользователь Сообщений: 539 |
#14 14.12.2021 18:49:52 Дмитрий(The_Prist) Щербаков
А может в вашем коде и FSO не нужен Зачем лишние объекты
Изменено: Евгений Смирнов — 14.12.2021 18:50:25 |
||
sokol92 Пользователь Сообщений: 4454 |
#15 14.12.2021 19:50:12 Я в коде из #6 изменил присвоение ArchivePath на
и успешно выполнил макрос. P.S. Увидел в названии темы «Permissio» и опешил — неужели Excel был уже в Древнем Риме? Изменено: sokol92 — 14.12.2021 20:02:59 Владимир |
||
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 14253 Профессиональная разработка приложений для MS Office |
#16 15.12.2021 11:44:27
моего кода там и нет Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
sokol92 Пользователь Сообщений: 4454 |
Дополнение к ответу Дмитрия. См. этo сообщение, п. 3.4. |
Олег Пользователь Сообщений: 4 |
Очень интересная картина. Как догадался Владимир, файлы лежат в сети. Заметил ещё вчера, что иногда, оно всё таки работает. Но очень иногда, он отрабатывал. Вчера думал показалось. Dir и Name пробовал, результат одинаковый. Заменители FO, типа Shell.Application использовать не умею. Подскажите пожалуйста, если можно. |
Дмитрий(The_Prist) Щербаков Спасибо за пояснения. Вчера сразу после вашего сообщения №3 я попробовал все действия с исходным файлом ( удалить, переместить, скопировать, переименовать) после SaveAs. На локальном компе все нормально. После сообщения №9 вчера, я так и понял в чем фишка вашего кода, почему он точно прокатит. А сегодня с утра заглянул снова в тему и наверно понял. 1. Вылазит Ошибка 70 « Отказано в доступе» значит недоступен либо исходный файл либо архивная папка 2. Вы добавили строку If Dir(NewFilePath, 16) = «». Здесь проверяется не только наличие файла в папке архива, но и доступность папки. Значит ошибка возникала из-за отказа в доступе к папке архива, а не к исходному файлу. Или я ошибаюсь? sokol92 Здравствуйте Владимир. Сообщение, п. 3.4. в вашей теме посмотрел. Скопировал на комп все пункты на всякий случай. Вряд ли конечно мне придется писать приложения на VBA в системах с различными версиями Windows. Начинающим такое не под силу. |
|
Олег Раз диск сетевой то мой код, не стоит пробовать, как подсказал sokol92 . Код Дмитрия Щербакова лучше. |
|
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 14253 Профессиональная разработка приложений для MS Office |
#21 15.12.2021 17:53:11
это больше по ошибке — в процессе проверки кода записал привычное обращение и забыл подменить на проверку ТС. Правильнее здесь применить то, что было у ТС:
и да и нет. Если недоступна папка — то и файл из неё недоступен. А приведенная мной конструкция проверяет именно наличие файла по указанному пути. Изменено: Дмитрий(The_Prist) Щербаков — 15.12.2021 17:54:35 Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||||
Евгений Смирнов Пользователь Сообщений: 539 |
#22 15.12.2021 18:16:44
Тогда проблема вообще не в коде. Код ТС нормальный, исходя из последних сообщений Дмитрия Надо обратить внимание на сообщением №15
Изменено: Евгений Смирнов — 16.12.2021 05:00:47 |
||||
sokol92 Пользователь Сообщений: 4454 |
#23 15.12.2021 18:50:32
Если Excel «подвис» во время копирования, то, естественно, файлы будут заблокированы. Более того, поскольку диск сетевой, то любой пользователь, у которого копирование «зависло», будет мешать остальным. Уточните у своих системщиков, какого типа сетевой диск (Windows, Linux Samba, …). Изменено: sokol92 — 15.12.2021 18:51:13 Владимир |
||
vikttur Пользователь Сообщений: 47199 |
#24 16.12.2021 00:59:25 Олег, сообщение сами исправите или модераторам после Вас убирать? |
Did you know that why you are getting or facing this Runtime Error 70 Permission Denied Windows PC code problem or frustrating with this error code problem on your Windows PC again & again then today you must surely have to read out and check this below Techinpost.com website blog post so that to get rid and get back from this error code problem permanently from you. So, all you to do is read this Runtime Error 70 Windows below post once fast,
This shows an error code message like,
Runtime Error 70 Windows
This is a pervasive runtime error problem and will appear when the users will not have sufficient security privileges or rights to the file is being used & when it is attempting to access a server from a remote app. This Runtime Error 70 Windows also caused when you have a corrupt registry. Basically, the DCOM server is utilized in a network to send a message to each workstation for them to communicate with the different processes. This error means that an attempt was made to write to a write-protected disk or to access a locked file. This Runtime Error 70 Windows includes the system PC freezes, crashes & the possible virus infection.
Causes of Runtime Error 70 Permission Denied Windows Code Issue:
- Permission denied pastel
- Windows PC error issue
- Corrupt Registry problem
So, here are some quick tips and tricks for efficiently fixing and solving this type of Runtime Error 70 Windows PC Code problem from you permanently.
How to Fix & Solve Runtime Error 70 Permission Denied Windows Code Issue
1. Enable the Authorization Checking on your Windows PC –
- Launch MTS Explorer
- Open the properties tab there
- Now, In Security option,
- Clear the Enable Authorization checking to set
- After completing, close the tab
- That’s it, done
By enabling the authorization, checking can fix and solve this access vba Runtime Error 70 Permission Denied Windows the problem.
2. Give Administrator Permissions to all Users on your Windows –
- Run the DCOM Config.
- Select the DCOM server app. from the list of available app.
- Select the ‘Properties‘ tab there or
- Double click the DCOM server app. in list
- Test the server with “Default Access Permissions” & “Default Launch Permissions” & the “Custom Configuration Permissions” there
- After completing, close all the tabs
- That’s it, done
By giving the administrator permissions to all the users on your Windows PC can quickly get back from this webtel Runtime Error 70 Permission Denied Windows 10 code problem.
3. Enable the DCOM (Distributed COM) on your Windows PC –
- Go to the start menu
- Search for & run the DCOM config. (DCOMENFG.EXE)
- Choose the default properties option there
- Ensure that the Enable Distributed COM on your PC is checked
(This value is stored in Windows Registry at this following location -Â HKEY_LOCAL_MACHINESoftwareMicrososftOLE) - After completing, close all the tabs
- That’s it, done
By enabling the DCOM (Distributed COM) can get rid out of this Visual Basic Runtime Error 70 Windows canon code problem from your device permanently.
4. Use Registry Cleaner to Clean all the Registry of your Windows –
Clean your registry by any registry cleaner software so that it can fix and solve this vba Runtime Error 70 Windows canon device code problem from your PC completely.
These are the quick and the best way methods to get quickly rid out of this Runtime Error 70 Permission Denied Windows PC Code problem from you entirely. Hope these solutions will surely help you to get back from this Runtime Error 70 Windows issue.
If you are facing or falling in this Runtime Error 70 Permission Denied Windows PC Code problem or any error problem, then comment down the error problem below so that we can fix and solve it too by our top best quick methods guides.
Writing a post about coding issues makes for awkward titles, but it’s likely the term people will search for when there’s a problem. For example, I received the error as it appears in this post’s title while running VBA code for an Excel application: Run-time error ’70’: Permission denied.
Clicking the “Debug” button, highlighted the following code segment:
Running VBScripts in the past was never an issue. However, I don’t use them for every application unless the situation warrants it. In this case, I am using regular expressions to parse entries that would otherwise be awkward and clumsy using traditional coding techniques.
Solving the Problem:
>>>>>>>>>>>>>>> If you’re in a hurry, you can watch our short video (3 minutes)! <<<<<<<<<<<<<<<
In todays world, it is very likely someone else has had a similar experience. In our case, we found a very close to match.
A quick search led me to Excel Forum and this concern: Re: “Permission denied” error on CreateObject(“vbscript.regexp”) with an accompanying link to a Malwarebytes forum that addresses “Application Hardening blocks access to vbscript.dll.” Malwarebytes Premium runs on my system, and I discovered that VBScript is considered an exploit and subsequently blocked.
Run the Malwarebytes application and click on the Settings icon. Then click the Security tab. Scroll down to find “Exploit Protection” and click on the Advanced settings button.
Note the settings of the checkboxes next to “Disable loading of VBScript libraries.” In my case, this box was checked for MS Office:
Uncheck the box and click the Apply button on the lower right corner of the window. Close then restart Excel for the changes to take effect.
Follow the above steps to enable VBScripts to run in Excel and other MS Office applications.
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Permission denied (Error 70) |
vblr6.chm50029 |
vblr6.chm50029 |
office |
b6822e40-c7e7-13e1-575e-632a99ad9926 |
06/08/2017 |
medium |
An attempt was made to write to a write-protected disk or to access a locked file. This error has the following causes and solutions:
-
You tried to open a write-protected file for sequential Output or Append. Open the file for Input or change the write-protection attribute of the file.
-
You tried to open a file on a disk that is write-protected for sequential Output or Append. Remove the write-protection device from the disk or open the file for Input.
-
You tried to write to a file that another process locked. Wait to open the file until the other process releases it.
-
You attempted to access the registry, but your user permissions don’t include this type of registry access.
On 32-bit Microsoft Windows systems, a user must have the correct permissions for access to the system registry. Change your permissions or have them changed by the system administrator.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]