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,5801 gold badge34 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,3333 gold badges20 silver badges48 bronze badges
Содержание
- В разрешении отказано (ошибка 70)
- Поддержка и обратная связь
- Vba run time error 70 permission denied
- Answered by:
- Question
- Vba run time error 70 permission denied
- Answered by:
- Question
- Thread: Run-time error ’70’: Permission denied ->when i run code
- Run-time error ’70’: Permission denied ->when i run code
- Vba run time error 70 permission denied
- Answered by:
- Question
- Answers
В разрешении отказано (ошибка 70)
Сделана попытка записать на диск, защищенный от записи, или получить доступ к заблокированному файлу. Эта ошибка имеет следующие причины и решения:
сделана попытка открыть защищенный от записи файл для последовательного вывода или добавления. Откройте файл для ввода или измените атрибут защиты файла от записи;
сделана попытка открыть файл на диске, защищенный от записи для последовательного вывода или добавления. Удалите с диска устройство защиты от записи или откройте файл для ввода;
сделана попытка записать в файл, заблокированный другим процессом. Чтобы открыть файл, дождитесь, пока процесс завершит работу с ним;
вы попытались получить доступ к реестру, но ваши разрешения пользователя не включают этот тип доступа к реестру.
В 32-разрядных операционных системах Microsoft Windows пользователь должен иметь правильные разрешения для доступа к реестру системы. Измените свои разрешения или обратитесь к системному администратору, чтобы он изменил их.
Для получения дополнительной информации выберите необходимый элемент и нажмите клавишу F1 (для Windows) или HELP (для Macintosh).
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Vba run time error 70 permission denied
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
The larger snippet of code below works perfectly on *most* Vista machines with Administrator rights? When it’s not Administator (and on some laptops with Administrator log in) I get «Runtime error 70, permission denied.» I believe this is because it’s trying to write a file to the C:/. I debugged, and the code gets caught up at:
cht1.Chart.Export strPath & «DailyBoard.jpeg»Export to Strpath
As soon as it tries to write the first file to the C:/ drive it generates the error.
I have researched runtime error 70 at nauseam and can’t find a work-a-round. I will not be able to change all the permissions settings on every computer this might try to be run on. Not all users will be able to log on as an Administrator. If there’s a way to bypass this problem, or to save directly to the users desktop, I’m ok with that? I just need to avoid this error on non-Administrator log ins. Any ideas?
This was tested on 5 Vista PC’s with Macro security settings «enabled» in Excel 2007.
2 logged on as Administrator, code worked perfectly
2 logged on as regular user without Admin rights, runtime error 70
1 logged on as Administrator (laptop), also runtime error 70
Code:
Sub Mail_Range_Outlook_Body()
‘ Working in Office 2000-2007
MsgBox «Please stop and make sure Outlook is open first, THEN click OK.»
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim sj
Dim em
Dim pic1 As Excel.Range
Dim pic2 As Excel.Range
Dim cht1 As Excel.ChartObject
Dim cht2 As Excel.ChartObject
Dim pic3 As Excel.Range
Dim cht3 As Excel.ChartObject
Const strPath As String = «C:»
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sj = ActiveSheet.Range(«F10»)
Set em = ActiveSheet.Range(«F11»)
Set pic1 = Sheet7.Range(«A1:M41»)
pic1.CopyPicture xlScreen, xlPicture
Set cht1 = ActiveSheet.ChartObjects.Add(0, 0, pic1.Width, pic1.Height)
cht1.Chart.Paste
cht1.Chart.Export strPath & «DailyBoard.jpeg»
cht1.Delete
Set cht = Nothing
Set cht1 = Nothing
Set pic2 = Sheet24.Range(«A1:G42»)
pic2.CopyPicture xlScreen, xlPicture
Set cht2 = ActiveSheet.ChartObjects.Add(0, 0, pic2.Width, pic2.Height)
cht2.Chart.Paste
cht2.Chart.Export strPath & «WeeklyInfo.jpeg»
cht2.Delete
Set cht = Nothing
Set cht2 = Nothing
Set pic3 = Sheets(«Email_Template»).Range(«A6:B63»).SpecialCells(xlCellTypeVisible)
pic3.CopyPicture xlScreen, xlPicture
Set cht3 = ActiveSheet.ChartObjects.Add(0, 0, pic3.Width, pic3.Height)
cht3.Chart.Paste
cht3.Chart.Export strPath & «NightlyEmail.jpeg»
cht3.Delete
Set cht = Nothing
Set cht2 = Nothing
Set rng = Nothing
On Error Resume Next
Set rng = Sheets(«Email_Template»).Range(«A6:B63»).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If rng Is Nothing Then
MsgBox «The selection is not a range or the sheet is protected» & _
vbNewLine & «please correct and try again.», vbOKOnly
Exit Sub
End If
Set OutApp = CreateObject(«Outlook.Application»)
OutApp.Session.Logon
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = em
.CC = «»
.BCC = «»
.Subject = sj
.HTMLBody = RangetoHTML(rng)
.Attachments.Add «c:NightlyEmail.jpeg»
.Attachments.Add «c:DailyBoard.jpeg»
.Attachments.Add «c:WeeklyInfo.jpeg»
.Display ‘or use .Send
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
Set rng = Nothing
Источник
Vba run time error 70 permission denied
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
The larger snippet of code below works perfectly on *most* Vista machines with Administrator rights? When it’s not Administator (and on some laptops with Administrator log in) I get «Runtime error 70, permission denied.» I believe this is because it’s trying to write a file to the C:/. I debugged, and the code gets caught up at:
cht1.Chart.Export strPath & «DailyBoard.jpeg»Export to Strpath
As soon as it tries to write the first file to the C:/ drive it generates the error.
I have researched runtime error 70 at nauseam and can’t find a work-a-round. I will not be able to change all the permissions settings on every computer this might try to be run on. Not all users will be able to log on as an Administrator. If there’s a way to bypass this problem, or to save directly to the users desktop, I’m ok with that? I just need to avoid this error on non-Administrator log ins. Any ideas?
This was tested on 5 Vista PC’s with Macro security settings «enabled» in Excel 2007.
2 logged on as Administrator, code worked perfectly
2 logged on as regular user without Admin rights, runtime error 70
1 logged on as Administrator (laptop), also runtime error 70
Code:
Sub Mail_Range_Outlook_Body()
‘ Working in Office 2000-2007
MsgBox «Please stop and make sure Outlook is open first, THEN click OK.»
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim sj
Dim em
Dim pic1 As Excel.Range
Dim pic2 As Excel.Range
Dim cht1 As Excel.ChartObject
Dim cht2 As Excel.ChartObject
Dim pic3 As Excel.Range
Dim cht3 As Excel.ChartObject
Const strPath As String = «C:»
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sj = ActiveSheet.Range(«F10»)
Set em = ActiveSheet.Range(«F11»)
Set pic1 = Sheet7.Range(«A1:M41»)
pic1.CopyPicture xlScreen, xlPicture
Set cht1 = ActiveSheet.ChartObjects.Add(0, 0, pic1.Width, pic1.Height)
cht1.Chart.Paste
cht1.Chart.Export strPath & «DailyBoard.jpeg»
cht1.Delete
Set cht = Nothing
Set cht1 = Nothing
Set pic2 = Sheet24.Range(«A1:G42»)
pic2.CopyPicture xlScreen, xlPicture
Set cht2 = ActiveSheet.ChartObjects.Add(0, 0, pic2.Width, pic2.Height)
cht2.Chart.Paste
cht2.Chart.Export strPath & «WeeklyInfo.jpeg»
cht2.Delete
Set cht = Nothing
Set cht2 = Nothing
Set pic3 = Sheets(«Email_Template»).Range(«A6:B63»).SpecialCells(xlCellTypeVisible)
pic3.CopyPicture xlScreen, xlPicture
Set cht3 = ActiveSheet.ChartObjects.Add(0, 0, pic3.Width, pic3.Height)
cht3.Chart.Paste
cht3.Chart.Export strPath & «NightlyEmail.jpeg»
cht3.Delete
Set cht = Nothing
Set cht2 = Nothing
Set rng = Nothing
On Error Resume Next
Set rng = Sheets(«Email_Template»).Range(«A6:B63»).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If rng Is Nothing Then
MsgBox «The selection is not a range or the sheet is protected» & _
vbNewLine & «please correct and try again.», vbOKOnly
Exit Sub
End If
Set OutApp = CreateObject(«Outlook.Application»)
OutApp.Session.Logon
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = em
.CC = «»
.BCC = «»
.Subject = sj
.HTMLBody = RangetoHTML(rng)
.Attachments.Add «c:NightlyEmail.jpeg»
.Attachments.Add «c:DailyBoard.jpeg»
.Attachments.Add «c:WeeklyInfo.jpeg»
.Display ‘or use .Send
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
Set rng = Nothing
Источник
Thread: Run-time error ’70’: Permission denied ->when i run code
Thread Tools
Display
Run-time error ’70’: Permission denied ->when i run code
I have been using this code for over a year and all of a sudden i can not run without getting the Run-time error ’70’: Permission denied.
I have tried just about every thing and all the webs info on this matter that i have found has not worked.
I have Windows 7 Ultimate. I noticed that my office 2007 completely and excel did an update back 10 days ago but i am sure i used it since then because i have had jobs to complete for the company i use this code on since then. The odd thing is that code very similar to this works for other websites on this same laptop. I have noticed some security pop up which i normally allow but i may have clicked not to once or twice, so i disabled avast security just to see, but nothing same issue. The next thing i thought maybe the owners of the Website itself changed something and now i can’t fill out there forms. So i opened the code with my other laptop that is Windows vista and it runs it fine with out any issues. I googled this issue and one post looked to have promise disabling User Account Control, but that did not work either and noticing also that my vista had it activate i should have known this was not going to work. I have three similar codes for the same website that i work with, but all three have the same issue even if i have been working with only one of them in the last few days.
On the code below if the cell «B24» were empty it would normally warn and say «Website is not opened yet», but it does not its steps threw this code and it acts as if the website url is in the «B24» cell and then tries to execute my code and it fails with the Run-time error we are now talking about. Note that it does this either with or without the «B24» cell having the URL in it.
I also thought internet explorer is causing it and is blocking the website, but i could not find it as a blocked website or popup.
So what could be causing this issue. Is it the code that i have not changed and always worked before, Excel program itself, security setting that i may have blocked and had nothing to do with avast security software, any suggestion welcome.
Last edited by SamT; 12-22-2014 at 11:59 AM . Reason: Formatted Code with # icon
Without a URL and the Owner and APN strings to test, it is hard to test.
Hopefully, you have tried Compile before a Run. If the Compile fails, I suspect it would be due to the MSIE browser object not being set in the References. You can check that as well in VBE’s Tools > References.
Tip: Now we use Code tags rather than VBA tags for posting code. Click the # icon to insert those or type them.
Источник
Vba run time error 70 permission denied
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I am using MS Access DataBase for my Application.
On the User InterFace as soon as i click on the ComboBox i start getting the the Error Message : Runtime Error ’70’ Permission Denied.
On the RowSource Property of ComboBox my setting in an Select Query.
I need Help on this, i have also checked the DCOM Properties.
Thanks And Regards
Answers
Well, I came accross this thread:
-17. How can I fix the Run-time error ’70’: Permission Denied?
A: Your computer may not have the necessary registry information for the class «Access.Application». Please run regedit to search Access.Application class. If it’s missing you may need to repair your Access. If you are running our converters on a Vista system you need to run them as Administrator.
Hope this helps,
Daniel van den Berg | Washington, USA | «Anticipate the difficult by managing the easy»
Источник
Jktu Пользователь Сообщений: 4 |
#1 14.12.2021 12:30:55 При открытии файла 1 сохраняю его как файл 2.
Средствами windows я переместить или удалить файл тоже не могу. Она говорит «Нет доступа или файл уже используется».
|
||||
Юрий М Модератор Сообщений: 60390 Контакты см. в профиле |
Jktu, зачем Вы пишете через строку? зачем растягивать сообщение? Не нужно жать на Enter по несколько раз. |
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
#3 14.12.2021 13:14:36
не запускать код из той книги, которую хотите в архив запихнуть. Ведь в момент попытки закинуть в архив файл с кодом — код-то выполняется, а значит файл по сути «открыт». Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
Олег Пользователь Сообщений: 4 |
Не совсем так. Я сохранил файл с новым именем и фактически макрос крутиться в новом файле. Запускать код снаружи нет возможности. Изменено: Олег — 14.12.2021 13:30:42 |
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 13997 Профессиональная разработка приложений для 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 |
Олег, зачем так рвать сообщение? |
Юрий М Модератор Сообщений: 60390 Контакты см. в профиле |
#8 14.12.2021 15:29:59
|
||
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 13997 Профессиональная разработка приложений для 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) Щербаков Пользователь Сообщений: 13997 Профессиональная разработка приложений для 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 Пользователь Сообщений: 4429 |
#15 14.12.2021 19:50:12 Я в коде из #6 изменил присвоение ArchivePath на
и успешно выполнил макрос. P.S. Увидел в названии темы «Permissio» и опешил — неужели Excel был уже в Древнем Риме? Изменено: sokol92 — 14.12.2021 20:02:59 Владимир |
||
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
#16 15.12.2021 11:44:27
моего кода там и нет Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
sokol92 Пользователь Сообщений: 4429 |
Дополнение к ответу Дмитрия. См. эт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) Щербаков Пользователь Сообщений: 13997 Профессиональная разработка приложений для 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 Пользователь Сообщений: 4429 |
#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 Олег, сообщение сами исправите или модераторам после Вас убирать? |
- Remove From My Forums
Excel 2007 — Runtime Error 70 — Permission Denied
-
Question
-
Aloha Friends:
The larger snippet of code below works perfectly on *most* Vista machines with Administrator rights? When it’s not Administator (and on some laptops with Administrator log in) I get «Runtime error 70, permission denied.» I believe this is because it’s trying to write a file to the C:/. I debugged, and the code gets caught up at:
cht1.Chart.Export strPath & «DailyBoard.jpeg»Export to Strpath
As soon as it tries to write the first file to the C:/ drive it generates the error.
I have researched runtime error 70 at nauseam and can’t find a work-a-round. I will not be able to change all the permissions settings on every computer this might try to be run on. Not all users will be able to log on as an Administrator. If there’s a way to bypass this problem, or to save directly to the users desktop, I’m ok with that? I just need to avoid this error on non-Administrator log ins. Any ideas?
This was tested on 5 Vista PC’s with Macro security settings «enabled» in Excel 2007.
2 logged on as Administrator, code worked perfectly
2 logged on as regular user without Admin rights, runtime error 70
1 logged on as Administrator (laptop), also runtime error 70Code:
Sub Mail_Range_Outlook_Body()
‘ Working in Office 2000-2007
MsgBox «Please stop and make sure Outlook is open first, THEN click OK.»Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim sj
Dim em
Dim pic1 As Excel.Range
Dim pic2 As Excel.Range
Dim cht1 As Excel.ChartObject
Dim cht2 As Excel.ChartObject
Dim pic3 As Excel.Range
Dim cht3 As Excel.ChartObjectConst strPath As String = «C:»
With Application
.EnableEvents = False
.ScreenUpdating = False
End WithSet sj = ActiveSheet.Range(«F10»)
Set em = ActiveSheet.Range(«F11»)Set pic1 = Sheet7.Range(«A1:M41»)
pic1.CopyPicture xlScreen, xlPicture
Set cht1 = ActiveSheet.ChartObjects.Add(0, 0, pic1.Width, pic1.Height)
cht1.Chart.Paste
cht1.Chart.Export strPath & «DailyBoard.jpeg»
cht1.Delete
Set cht = Nothing
Set cht1 = NothingSet pic2 = Sheet24.Range(«A1:G42»)
pic2.CopyPicture xlScreen, xlPicture
Set cht2 = ActiveSheet.ChartObjects.Add(0, 0, pic2.Width, pic2.Height)
cht2.Chart.Paste
cht2.Chart.Export strPath & «WeeklyInfo.jpeg»
cht2.Delete
Set cht = Nothing
Set cht2 = NothingSet pic3 = Sheets(«Email_Template»).Range(«A6:B63»).SpecialCells(xlCellTypeVisible)
pic3.CopyPicture xlScreen, xlPicture
Set cht3 = ActiveSheet.ChartObjects.Add(0, 0, pic3.Width, pic3.Height)
cht3.Chart.Paste
cht3.Chart.Export strPath & «NightlyEmail.jpeg»
cht3.Delete
Set cht = Nothing
Set cht2 = NothingSet rng = Nothing
On Error Resume Next
Set rng = Sheets(«Email_Template»).Range(«A6:B63»).SpecialCells(xlCellTypeVisible)
On Error GoTo 0If rng Is Nothing Then
MsgBox «The selection is not a range or the sheet is protected» & _
vbNewLine & «please correct and try again.», vbOKOnly
Exit Sub
End IfSet OutApp = CreateObject(«Outlook.Application»)
OutApp.Session.Logon
Set OutMail = OutApp.CreateItem(0)On Error Resume Next
With OutMail
.To = em
.CC = «»
.BCC = «»
.Subject = sj
.HTMLBody = RangetoHTML(rng)
.Attachments.Add «c:NightlyEmail.jpeg»
.Attachments.Add «c:DailyBoard.jpeg»
.Attachments.Add «c:WeeklyInfo.jpeg»
.Display ‘or use .Send
End With
On Error GoTo 0With Application
.EnableEvents = True
.ScreenUpdating = True
End WithSet OutMail = Nothing
Set OutApp = Nothing
Set rng = Nothing-
Edited by
Monday, October 12, 2009 4:00 PM
Edit content -
Moved by
Martin Xie — MSFT
Tuesday, October 13, 2009 9:38 AM
Move it to VBA forum for better responses. (From:Visual Basic Language)
-
Edited by
Answers
-
The Vista UAC may be to blame. So if you can direct the output to a folder that is not locked, that would be the easiest solution. For example, you can direct output to MyDocuments.
-
Marked as answer by
Tim Li
Monday, October 19, 2009 3:03 AM
-
Marked as answer by
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.
- Remove From My Forums
-
Вопрос
-
Hi there
Thank you in advance for taking the time to check this out.
Objective:
I have 2 combo boxes, one is dependent on what has been selected in the first combo box (dynamic named range), they work fine except for an irritating error when the user accidentally clicks in the empty
Cmbox_IncCategory and it won’t allow the user to go back to the
cmbx_Category_Type box if the user forgot he had to make a selection from that first before selecting the
Cmbox_IncCategory.The error that pops up is “Invalid property value”.
I tried having text in there to say “please select from Cmbox_IncCategory first, but that didn’t fix it.
I tried to ‘If error resume next’ but that didn’t like it either. Now I am stumped.Main combo box= cmbx_Category_Type
2nd combo box (displaying a list dependent on what was selected in Main combo box)= Cmbox_IncCategoryI know there must be a way to fix it so that if a user clicks on the combo box, but doesn’t make a selection it won’t lock up the form.
Yes, it is a mandatory field, and I was considering using a message box to advise the user that this must be completed, but I am not sure how to do it (and avoid the errors
)
Here’s the current code I have for the combo boxes.
Me.Cmbox_IncCategory = "" 'Clears the contents of the 2nd combobox when another category is chosen On Error Resume Next 'I can't seem to have the Incident Category combobox to be empty when the form is open _ I have tried Cmbox_IncCategory.Value = "", but I get an error. I then tried Cmbox_IncCategory.text = "" _ but also get the error. I don't know how else to get it to work .. I tried both codes in the _ form_initialize, but get an error ... I'm stumped ! Select Case Me.cmbx_Category_Type Case "Crime" Me.Cmbox_IncCategory.RowSource = "Inc_Cat_CRIME" Case "Property Damage - Minor - NS" Me.Cmbox_IncCategory.RowSource = "Inc_Cat_PROPRTY_NS" Case "Property Damage - Significant - S" Me.Cmbox_IncCategory.RowSource = "Inc_Cat_Proprty_S" Case "Safety" Me.Cmbox_IncCategory.RowSource = "Inc_Cat_SAFETY" Case "Security Breach" Me.Cmbox_IncCategory.RowSource = "Inc_Cat_BREACH_S" Case "Support" Me.Cmbox_IncCategory.RowSource = "Inc_Cat_SUPPORT" Case "Vehicle" Me.Cmbox_IncCategory.RowSource = "Inc_Cat_VEHICLE_S" End Select End Sub
I’d be really grateful if someone could help me out, or perhaps direct me to where I might find some coding that will achieve the result I am seeking.
With much gratitude,
TheShyButterfly
Hope you have a terrific day, theShyButterfly
-
Изменено
31 марта 2015 г. 8:16
Please delete this post — it went into the wrong forum — sorry
-
Изменено
Ответы
-
However, with regards to the Incident Categories code…. I am getting a «Run-Time error 70 — Permission Denied».
I don’t like being ‘denied’ LOL …
Yes, but you denied yourself.
Hint:
When you get an error within a Userform, usually you can not see the line where it happens inside the Userform, because the VBA-editor stops only in regular modules. In that case change the VBA error settings (temporary) from «Unhandled Errors» (default
setting) to «All Errors» (or «Class Module»):When you run your form now, it stops at this line:
cmbx_Incident_Type.List = GetValuesBelowNamedCell(«Inc_Main_Category»)At this point select cmbx_Incident_Type, press SHIFT-F9 and click Add to add the variable to the watch window.
Click on the «+» sign on the left side of «cmbx_Incident_Type» inside the watch window to see all the properties and scroll down till RowSource.As you see there is the value «Inc_Main_Category» inside RowSource, which you have set manually in the past.
The RowSource and List properties are «connected», both fill items into the combo box, means you can use only one of them.
Remove the value from the RowSource property of the control and the error is gone.
BTW, you can also execute this before the line above, to remove the value temporary:
cmbx_Incident_Type.RowSource = «»BTW2, add this line
Me.cmbox_IncCategory.ListIndex = -1
to
Sub cmbx_Incident_Type_Change
to clear previous selections.Andreas.
-
Предложено в качестве ответа
George123345
9 апреля 2015 г. 6:37 -
Помечено в качестве ответа
George123345
9 апреля 2015 г. 6:37
-
Предложено в качестве ответа