Visual basic runtime error 70 permission denied

В разрешении отказано (ошибка 70) Сделана попытка записать на диск, защищенный от записи, или получить доступ к заблокированному файлу. Эта ошибка имеет следующие причины и решения: сделана попытка открыть защищенный от записи файл для последовательного вывода или добавления. Откройте файл для ввода или измените атрибут защиты файла от записи; сделана попытка открыть файл на […]

Содержание

  1. В разрешении отказано (ошибка 70)
  2. Поддержка и обратная связь
  3. Vba run time error 70 permission denied
  4. Answered by:
  5. Question
  6. Vba run time error 70 permission denied
  7. Answered by:
  8. Question
  9. Thread: Run-time error ’70’: Permission denied ->when i run code
  10. Run-time error ’70’: Permission denied ->when i run code
  11. Vba run time error 70 permission denied
  12. Answered by:
  13. Question
  14. 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»

Источник

  • Remove From My Forums

 locked

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 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 

    • 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)

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

 

Jktu

Пользователь

Сообщений: 4
Регистрация: 14.12.2021

#1

14.12.2021 12:30:55

При открытии файла 1 сохраняю его как файл 2.
Первый файл хочу переместить в архив, при этом получаю ошибку

Цитата
Run-time error ’70’
Permission denied

Средствами windows я переместить или удалить файл тоже не могу. Она говорит «Нет доступа или файл уже используется».
Как отпустить файл 1 после saveas?

Код
ThisWorkbook.SaveAs NewFilePath, FileFormat:=52
fso.MoveFile FilePath, ArchivePath
 

Юрий М

Модератор

Сообщений: 60390
Регистрация: 14.09.2012

Контакты см. в профиле

Jktu,  зачем Вы пишете через строку? зачем растягивать сообщение? Не нужно жать на Enter по несколько раз.
И код следует оформлять соответствующим тегом: ищите кнопку <…> и приведите своё сообщение в порядок.

 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 13997
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#3

14.12.2021 13:14:36

Цитата
написал:
Как отпустить файл 1 после saveas?

не запускать код из той книги, которую хотите в архив запихнуть. Ведь в момент попытки закинуть в архив файл с кодом — код-то выполняется, а значит файл по сути «открыт».

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Олег

Пользователь

Сообщений: 4
Регистрация: 14.12.2021

Не совсем так. Я сохранил файл с новым именем и фактически макрос крутиться в новом файле.
Как освободить старый файл?

Запускать код снаружи нет возможности.

Изменено: Олег14.12.2021 13:30:42

 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 13997
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#5

14.12.2021 14:05:48

Цитата
написал:
сохранил файл с новым именем и фактически макрос крутиться в новом файле

это факт или Вы так думаете? :)
Судя по куску приложенного кода — Вы делаете SaveAs ровно тем же кодом, что и пытаетесь потом архивировать. Нигде не вижу отсылки в новый файл.
Если FilePath = ThisWorkbook — то Вы ошибаетесь, полагая, что что-то само запустилось в новом файле. Ваш исходный файл занят выполнением кода. То, что Вы сделали до этого SaveAs не прекращает работу кода. А по Вашей логике — код должен был бы завершиться уже сразу после SaveAs и до архивации дело бы вообще не дошло.
Если ThisWorkbook это ровно та книга, которую хотите архивировать, то правильнее делать SaveCopyAs и архивировать эту копию. Она точно не будет занята никаким процессом, потому что весь процесс будет в файле с кодом.

Цитата
написал:
Средствами windows я переместить или удалить файл тоже не могу

поясните так же — в какой момент Вы это пробуете делать? Это только с одним файлом или с любым файлом в этой папке?

Изменено: Дмитрий(The_Prist) Щербаков14.12.2021 14:08:43

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Олег

Пользователь

Сообщений: 4
Регистрация: 14.12.2021

#6

14.12.2021 14:44:16

Я так думал. Я предполагаю, что я ошибался и ищу где именно.

Судя по тому, что я вижу название нового файла в дереве проекта, я сделал вывод, что код крутится в новом файле.

Диспетчер задач показывает 2 процесса excel после saveas.

Я пытался вызывать новый макрос на перемещение файла. Результат не поменялся.

Поэтому спрашиваю совет у опытных.

SaveCopyAs, тоже вариант, но не идеальный.

1) в итоге мне нужно иметь файл с новым именем в открытом состоянии. возможно стоит поискать переименование.
2) файл в папке с архивами желательно иметь без изменения даты.
3) в исходной папке старый файл надо удалить.

Более полный код:

Код
Sub save_file()

Set fso = CreateObject("Scripting.FileSystemObject")

FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))

NewFilePath = Left(FilePath, Len(FilePath) - Len(FileOnly)) + Format(Now, "yyyy.mm.dd") + "New.xlsm"

ArchivePath = "s:"

If Not fso.FileExists(NewFilePath) Then
   ThisWorkbook.SaveAs NewFilePath, FileFormat:=52
   fso.MoveFile FilePath, ArchivePath
End If
End Sub

Надеюсь будут ещё идеи.

Изменено: Олег14.12.2021 15:04:59

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

Олег, зачем так рвать сообщение?

 

Юрий М

Модератор

Сообщений: 60390
Регистрация: 14.09.2012

Контакты см. в профиле

#8

14.12.2021 15:29:59

Цитата
Юрий М написал:
Не нужно жать на Enter по несколько раз
 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 13997
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#9

14.12.2021 16:31:07

Может попробовать правильно перемещать?

Код
Sub save_file()
    Dim FilePath$, FileOnly$, PathOnly$, ArchivePath$, NewFilePath$, FName$
    Dim fso As Object, objFile As Object
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    FilePath = ThisWorkbook.FullName
    FileOnly = ThisWorkbook.Name
    PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))
    
    FName = Format(Now, "yyyy.mm.dd") & "New.xlsm"
    NewFilePath = Left(FilePath, Len(FilePath) - Len(FileOnly)) & FName
     
    ArchivePath = "d:" & FName 'для перемещения нужен полный путь к файлу, а не только путь к папке
    If Dir(NewFilePath, 16) = "" Then
       ThisWorkbook.SaveAs NewFilePath, FileFormat:=52
       fso.MoveFile FilePath, ArchivePath
    End If
End Sub

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Евгений Смирнов

Пользователь

Сообщений: 539
Регистрация: 18.02.2021

#10

14.12.2021 16:54:40

Цитата
Дмитрий(The_Prist) Щербаков написал Ваш исходный файл занят выполнением кода.

Если исходный файл занят  после оператора SaveAs мы в следующих строчках можем исходный файл( удалить, переместить, скопировать, переименовать)?
Я думал что с занятым файлом эти действия недоступны

Изменено: Евгений Смирнов14.12.2021 17:13:51

 

Евгений Смирнов, тут дело-то не простое…С одной стороны — файл не должен быть занят, если мы делаем Save As из меню. Там никаких отсылок на файл не остается. Но если делаем кодом — то какое-то время файл еще используется системой, т.к. его код был скомпилирован и он на текущий момент выполняется(да, там происходят процессы чуть иные, но будем считать так — файл все равно какое-то время после SaveAs используется). Сколько файл будет заблокирован зависит от того, где как и что происходит. Например, на локальном диске это будут скорее всего миллисекунды(опять же зависит от размера файла). После выполнения всех команд кода файл должен быть успешно перемещен в любом случае. А вот на сетевом(или что-то вроде виртуального рабочего стола) — это может занять и больше времени и вообще иначе отработать. Вроде код уже выполнил SaveAs и файл создался, и новый вроде как сейчас используется, а не исходный — но система все еще считает исходный файл занятым. И тут разные факторы могут повлиять на то, когда система его разблокирует и разблокирует ли вообще без презапуска Excel.
Приложенный мной код выше должен работать по сути. И если все равно доступ будет заблокирован — значит дело уже больше в ОС, а не в кодах.

Изменено: Дмитрий(The_Prist) Щербаков14.12.2021 17:25:55

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Евгений Смирнов

Пользователь

Сообщений: 539
Регистрация: 18.02.2021

#12

14.12.2021 17:28:25

Дмитрий(The_Prist) Щербаков

Спасибо за пояснения. Но тогда  ещё как вариант после SaveAs можно задержку воткнуть.

Код
Application.Wait (Now + TimeValue("00:00:10")) 'Задержка выполнения макроса на 10 сек
 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 13997
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#13

14.12.2021 17:37:58

Цитата
Евгений Смирнов написал:
можно задержку воткнуть

а смысл? Сначала надо диагностировать, а потом костыли вешать. А если файл и без задержек нормально переместиться? Ждать 10 секунд? Не самая лучшая идея. К тому же метод Wait опять же может удерживать файл в процессах. Так же, если проблема в ОС — файл может вообще не получится освободить ни через 10 секунд, ни через полчаса.
Поэтому повторюсь: все фиксированные задержки лучше делать только после четкого понимания проблемы. Иначе они только хуже сделают. Если уж на то пошло, то лучше обход ошибок и цикл Do While до тех пор, пока не получится выполнить операцию. Но здесь тоже надо аккуратно и выставлять какие-то границы(таймер на какой-то лимит, счетчик и т.п.), иначе есть шанс попасть в бесконечный цикл.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Евгений Смирнов

Пользователь

Сообщений: 539
Регистрация: 18.02.2021

#14

14.12.2021 18:49:52

Дмитрий(The_Prist) Щербаков

А может в вашем коде и FSO не нужен Зачем лишние объекты

Код
Sub save_file1()
    Dim FilePath$, FileOnly$, PathOnly$, ArchivePath$, NewFilePath$, FName$
     
    FilePath = ThisWorkbook.FullName
    FileOnly = ThisWorkbook.Name
    PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))
     
    FName = Format(Now, "yyyy.mm.dd") & "New.xlsm"
    NewFilePath = Left(FilePath, Len(FilePath) - Len(FileOnly)) & FName
      
    ArchivePath = "d:" & FName 'для перемещения нужен полный путь к файлу, а не только путь к папке
    If Dir(NewFilePath, 16) = "" Then
       ThisWorkbook.SaveAs NewFilePath, FileFormat:=52
       Name FilePath As ArchivePath
    End If
End Sub

Изменено: Евгений Смирнов14.12.2021 18:50:25

 

sokol92

Пользователь

Сообщений: 4429
Регистрация: 10.09.2017

#15

14.12.2021 19:50:12

Я в коде из #6 изменил присвоение ArchivePath на

Код
ArchivePath = "C:temptemp"

и успешно выполнил макрос.
Писать файлы к корень диска (S:) — моветон, проверьте есть ли соответствующий доступ.
Повторите свои действия для любого существующего каталога ArchivePath, к которому заведомо есть доступ по записи. Перед экcпериментом закройте Excel и снимите все фоновые процессы Excel через Диспетчер задач.

P.S. Увидел в названии темы «Permissio» и опешил — неужели Excel был уже в Древнем Риме?  :)

Изменено: sokol9214.12.2021 20:02:59

Владимир

 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 13997
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#16

15.12.2021 11:44:27

Цитата
Евгений Смирнов написал:
А может в вашем коде и FSO не нужен

моего кода там и нет :) Я не стал переписывать полностью код ТС-а, чтобы ему больше был понятен смысл дополнений. Плюс имейте ввиду, что Dir не всегда корректно работает с сетевыми дисками. Поэтому я не стал ничего менять у ТС — пусть использует то, что больше нравится и что больше подходит. Вдруг он с сетевым диском это будет применять…

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

sokol92

Пользователь

Сообщений: 4429
Регистрация: 10.09.2017

Дополнение к ответу Дмитрия. См.

этo

сообщение, п. 3.4.

 

Олег

Пользователь

Сообщений: 4
Регистрация: 14.12.2021

Очень интересная картина.

Как  догадался Владимир, файлы лежат в сети.
S; , это  тут выложено для сокращения. На самом там что-то типа S:Проект   и т.п.
Пробовали менять написание пути типа S:Проект  или \ServerПроект

Заметил ещё вчера, что иногда, оно всё таки работает. Но очень иногда, он отрабатывал. Вчера думал показалось.
При замене сетевого пути на локальный, типа C:temptemp, действительно всё срабатывает.
Удивляет ситуация ещё сильнее.
Доступ к конечным папкам точно есть.
Пробовал ставить wait до 40 сек., далее не имеет смысла, т.к. с файлом нужно работать.
К тому же если после ошибки перехожу в debug, проходит несколько минут и файл не копируется ни кодом не из винды.

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
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#21

15.12.2021 17:53:11

Цитата
Евгений Смирнов написал:
Вы добавили строку If Dir(NewFilePath, 16) = «».

это больше по ошибке — в процессе проверки кода записал привычное обращение и забыл подменить на проверку ТС. Правильнее здесь применить то, что было у ТС:

Код
If Not fso.FileExists(NewFilePath) Then

Цитата
Евгений Смирнов написал:
ошибка возникала из-за отказа в доступе к папке архива, а не к исходному файлу

и да и нет. Если недоступна папка — то и файл из неё недоступен. А приведенная мной конструкция проверяет именно наличие файла по указанному пути.

Изменено: Дмитрий(The_Prist) Щербаков15.12.2021 17:54:35

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Евгений Смирнов

Пользователь

Сообщений: 539
Регистрация: 18.02.2021

#22

15.12.2021 18:16:44

Цитата
Олег написал К тому же если после ошибки перехожу в debug, проходит несколько минут и файл не копируется ни кодом не из винды.

Тогда  проблема вообще не в коде.  Код ТС нормальный, исходя из последних сообщений Дмитрия Надо обратить внимание на сообщением №15

Цитата
Sokol 92 Перед экcпериментом закройте Excel и снимите все фоновые процессы Excel через Диспетчер задач

Изменено: Евгений Смирнов16.12.2021 05:00:47

 

sokol92

Пользователь

Сообщений: 4429
Регистрация: 10.09.2017

#23

15.12.2021 18:50:32

Цитата
написал:
проходит несколько минут и файл не копируется ни кодом не из винды

Если Excel «подвис» во время копирования, то, естественно, файлы будут заблокированы. Более того, поскольку диск сетевой, то любой пользователь, у которого копирование «зависло», будет мешать остальным.

Уточните у своих системщиков, какого типа сетевой диск (Windows, Linux Samba, …).

Изменено: sokol9215.12.2021 18:51:13

Владимир

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#24

16.12.2021 00:59:25

Олег, сообщение сами исправите или модераторам после Вас убирать?
Помощь скрыта

RRS feed

  • Remove From My Forums
  • Question

    • Moved by
      Liliane Teng
      Monday, July 26, 2010 2:00 AM
      Please repost on appropriate forum for better support (From:Visual Basic General)

Answers

    • Marked as answer by
      Mr. Wharty
      Friday, June 1, 2012 6:30 AM
  • I had the same problem
    and
     found the solution by
    deleting the file
     msvbvm60.dll which
    is in
     the application folder. This
    is because the
     file must exist
    only
     system32.

    • Marked as answer by
      Mr. Wharty
      Friday, June 1, 2012 6:31 AM

All replies

    • Marked as answer by
      Mr. Wharty
      Friday, June 1, 2012 6:30 AM
  • Hello Jandrick,

    Thanks for your post.

    This forum is for VB.NET questions only. Please repost on appropriate forum as Cor suggested for better and quicker support. Thanks for understanding.

    Best regards,

    Liliane


    Please mark the replies as answers if they help and unmark them if they provide no help. Thanks

  • ‘You have to have ms scripting runtime referenced

    -Dim WshShell As Object

    Set WshShell = CreateObject(«WScript.Shell»)

    WshShell.SendKeys «{Tab}»

    Try This. Rajkumar — GTN — India

    • Proposed as answer by
      Philkos
      Wednesday, January 11, 2012 11:00 AM

  • ‘You have to have ms scripting runtime referenced

    -Dim WshShell As Object

    Set WshShell = CreateObject(«WScript.Shell»)

    WshShell.SendKeys «{Tab}»

    Try This. Rajkumar — GTN — India

    I try it …. failed….  Any other Method? Can you please mail to me? <removed> Tks!

    • Edited by
      Mr. Wharty
      Friday, June 1, 2012 6:31 AM
      Removed email address

  • I had the same problem
    and
     found the solution by
    deleting the file
     msvbvm60.dll which
    is in
     the application folder. This
    is because the
     file must exist
    only
     system32.

    • Marked as answer by
      Mr. Wharty
      Friday, June 1, 2012 6:31 AM

  • Dim WshShell As Object

    Set WshShell = CreateObject(«WScript.Shell»)

    WshShell.SendKeys «{Tab}»

    ===================================================

    SendKeys «{Tab}» problem Solved in Windows8.

    What i did ………keep UAC settings  to (no notification) and use above code.

    problem solved…………… thanks to

    rakha india1………Thanks  a lot.

    Can You give me a trick how vb6 project can be converted to vb.net…………?

    • Edited by
      MASTERSAM2012
      Wednesday, January 9, 2013 12:03 PM

  • Thank you so much, Rajkumar!  I have a couple of Access97 apps that need to run on Windows 8 and SendKeys gave runtime error 70 — permission denied — even with UAC turned off.  These 3 little lines of code resolved the issue.  You made my
    day!

  • MasterSam,

    The best way to convert your vb6 project to vb .net is to load visual studio 2008 and try to open the vb6 project with it, then go thru the steps to convert, after that you need to fix about 20% of the project in order to work.


    Oscar

  • Thanks Rjkumar

    Works Perfect…!!

  • Thanks bro. It’s working. It is a good code…

  • Thank u very much Mr. Rajkumar — GTN — India 

    for the Help (Using WinShell)

В разрешении отказано (ошибка 70)

Сделана попытка записать на диск, защищенный от записи, или получить доступ к заблокированному файлу. Эта ошибка имеет следующие причины и решения:

сделана попытка открыть защищенный от записи файл для последовательного вывода или добавления. Откройте файл для ввода или измените атрибут защиты файла от записи;

сделана попытка открыть файл на диске, защищенный от записи для последовательного вывода или добавления. Удалите с диска устройство защиты от записи или откройте файл для ввода;

сделана попытка записать в файл, заблокированный другим процессом. Чтобы открыть файл, дождитесь, пока процесс завершит работу с ним;

вы попытались получить доступ к реестру, но ваши разрешения пользователя не включают этот тип доступа к реестру.

В 32-разрядных операционных системах Microsoft Windows пользователь должен иметь правильные разрешения для доступа к реестру системы. Измените свои разрешения или обратитесь к системному администратору, чтобы он изменил их.

Для получения дополнительной информации выберите необходимый элемент и нажмите клавишу F1 (для Windows) или HELP (для Macintosh).

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Methods to Fix Runtime Error 70 Permission Denied Windows Code Issue

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.

Источник

Runtime error permission denied 70 vba

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

Источник

Runtime error permission denied 70 vba

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»

Источник

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.

Источник

  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • Permission Denied Run-time Error 70 trying to move folder with File System Object

  1. Jul 5th, 2016, 10:33 AM


    #1

    Cody120 is offline

    Thread Starter


    New Member


    Permission Denied Run-time Error 70 trying to move folder with File System Object

    Hi,

    I am trying to do something very simple- move a folder from the desktop to a shared network drive with visual basic (the actual program is more involved, but I am getting an error message on this step).

    My code is as follows:

    ‘—————
    Dim fso As FileSystemObject
    Set fso = CreateObject(«Scripting.FileSystemObject»)
    fso.MoveFolder «W:Test» & txtJob.Text, «C:UsersCodyDesktopTesting» ‘Moves folder
    ‘—————

    When running this, I get a message saying «Run-time error 70: Permission Denied».
    I am using Windows 7, but some of the other computers on the shared network are using Windows 10 (they recently upgraded) (I don’t know if that would make a difference). I am using vb6. I have administrative privileges and even tried «run as administrator», so not sure why I would be denied permission to anything. I am able to manually move files to and from the shared drive. I am able to do other things with vb6, such as creating a folder with the file system object on the shared drive.

    Oddly, one of my other computers was running a macro fine and after upgrading to windows 10 gives an error saying «elevation required.» It uses a slightly different language, but I am mentioning it in case the two errors are related to security settings somehow.

    Any suggestions on how to resolve this error would be greatly appreciated. Thanks for your time!


  2. Jul 5th, 2016, 11:08 AM


    #2

    Re: Permission Denied Run-time Error 70 trying to move folder with File System Object

    MoveFile not MoveFolder?
    Unless you’re moving a folder, in which case if the folder already exists MoveFolder throws an Error

    see: https://msdn.microsoft.com/en-us/lib…(v=vs.84).aspx


  3. Jul 5th, 2016, 12:37 PM


    #3

    Re: Permission Denied Run-time Error 70 trying to move folder with File System Object

    I’m trying to recall whether you get an error 70 on this if the folder already exists at the destination.

    But note that having local admin rights doesn’t mean you have them on the network share server.

    Oops, you are going the other way! Disregard the previous remark, and:

    Code:

    fso.MoveFolder source, destination

    Last edited by dilettante; Jul 5th, 2016 at 12:42 PM.


  4. Jul 5th, 2016, 02:35 PM


    #4

    Cody120 is offline

    Thread Starter


    New Member


    Re: Permission Denied Run-time Error 70 trying to move folder with File System Object

    Thanks for the responses! Yes, I am moving a folder (not a file, sorry for the confusion!). I am moving the folder back and forth, so part of my code is moving one way and a different part of my code moves the other way, I just posted the code for one of the ways.

    The folder does not already exist in the destination location, so that isn’t an issue. I did not have «full control» selected, but I had all other permissions for the network drive. After checking «full control» for the network drive, I still get the same error.

    Any other suggestions?


  5. Jul 5th, 2016, 04:36 PM


    #5

    Re: Permission Denied Run-time Error 70 trying to move folder with File System Object

    does movefolder (or file) work at all across drives?
    try copyfolder and deletefolder

    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete


  6. Jul 6th, 2016, 12:18 AM


    #6

    Re: Permission Denied Run-time Error 70 trying to move folder with File System Object

    If you go into Explorer and manually drag or copy/paste it to the new location, does it work? If it does, you could almost certainly just go through the same high level things Explorer does. You can even invoke the drag/drop through code (not actually moving the mouse cursor to do it, just going through the interface that is called when you do physically use the mouse)

    I’m sure the other high level things like IFileOperation would work too, but this is kinda fun (and will also put up the progress dialog):

    Code:

    Public Declare Function SHGetDesktopFolder Lib "shell32" (ppshf As IShellFolder) As Long ' Retrieves the IShellFolder interface for the desktop folder.
    Public Declare Function ILCreateFromPathW Lib "shell32" (ByVal pwszPath As Long) As Long
    Public Declare Function SHCreateFileDataObject Lib "shell32" Alias "#740" (ByVal pidlFolder As Long, ByVal cidl As Long, ByVal apidl As Long, pDataInner As Any, ppDataObj As oleexp3.IDataObject) As Long
    Public Declare Sub CoTaskMemFree Lib "ole32.dll" (ByVal PV As Long) ' Frees memory allocated by the shell
    
    
    Public Function MoveViaDrop(sSource As String, sDest As String) As Long
    'Moves via dragdrop interfaces. Source and dest can be anything you can
    'drag from and drop onto in Explorer.
    Dim idoSrc As oleexp3.IDataObject
    Dim pDT As IDropTarget
    Dim pidlDest As Long
    Dim pidlSrc As Long
    
    pidlDest = ILCreateFromPathW(StrPtr(sDest))
    isfDesktop.GetUIObjectOf 0&, 1&, pidlDest, IID_IDropTarget, 0&, pDT
    If (pDT Is Nothing) = False Then
        pidlSrc = ILCreateFromPathW(StrPtr(sSource))
        Call SHCreateFileDataObject(VarPtr(0&), 1&, VarPtr(pidlSrc), ByVal 0&, idoSrc)
        If (idoSrc Is Nothing) = False Then
            pDT.DragEnter idoSrc, MK_LBUTTON, 0&, 0&, DROPEFFECT_MOVE
            pDT.Drop idoSrc, MK_LBUTTON, 0&, 0&, DROPEFFECT_MOVE
            MoveViaDrop = 1
        Else
            MoveViaDrop = -1
        End If
    Else
        MoveViaDrop = -2
    End If
    Call CoTaskMemFree(pidlSrc)
    Call CoTaskMemFree(pidlDest)
    
    End Function
    Public Function isfDesktop() As IShellFolder
      Static isf As IShellFolder
      If (isf Is Nothing) Then Call SHGetDesktopFolder(isf)
      Set isfDesktop = isf
    End Function

    (uses my typelib oleexp + mIID module)

    Last edited by fafalone; Jul 6th, 2016 at 12:37 AM.


  7. Jul 6th, 2016, 12:29 AM


    #7

    Re: Permission Denied Run-time Error 70 trying to move folder with File System Object

    Quote Originally Posted by dilettante
    View Post

    I’m trying to recall whether you get an error 70 on this if the folder already exists at the destination.

    dilettante you are correct in your guess.
    Error 70 — File is in use
    Error 75 — No admin Permissions to write to disk.

    off course it’s not set in stone, but these are the common scenarios.

    The folder does not already exist in the destination location, so that isn’t an issue. I did not have «full control» selected, but I had all other permissions for the network drive. After checking «full control» for the network drive, I still get the same error.

    trying to start a new project and only do a copy of a file, a different file different project, just to see if this method specifically works for you.
    also,I suggest you use UNC paths not mapped drive letters (\serverNameOrIpfolderonefile.txt instead of L:file.txt) it caused me headaches before for no obvious reasons.

    p.s: restart your pc


  8. Jul 6th, 2016, 08:55 AM


    #8

    Cody120 is offline

    Thread Starter


    New Member


    Re: Permission Denied Run-time Error 70 trying to move folder with File System Object

    (uses my typelib oleexp + mIID module)

    fafalone- I am not sure what typelib oleexp and mIID module are. I checked the project references and did not see those. Also, I am more of a novice-intermediate coder, so it was a little hard to follow the code. I want to be able to maintain the code and understand it.

    westconn1 and stum- copy folder does work for me I can probably do what I need to do with just copy folder and delete folder, but I’d still like to know why move folder gives me that error message both for learning and in case something similar happens with copy folder down the line (plus it makes the code cleaner to just have 1 command, move folder, instead of 2). I am able to move a file or folder from one location on the C: drive to another location on the C: drive. It’s just not working with the mapped drives.

    stum- I tried UNC paths as well, and this still gave me the same error for movefolder. So what would count as a file/folder being in use? I have coworkers who are using the mapped drive but not this particularly folder. Or maybe after handling a file I need to empty some memory somewhere or else the program still has it in the background?

    Any other reasons why move folder would give me this error (runtime error 70 permission denied)?


  9. Jul 6th, 2016, 04:18 PM


    #9

    Re: Permission Denied Run-time Error 70 trying to move folder with File System Object

    from msdn, read the last paragraph, indicates that movefolder may not work from different logical drives, even on same machine or physical hard drive

    MoveFolder Method

    Description

    Moves one or more folders from one location to another.

    Syntax

    object.MoveFolder source, destination

    The MoveFolder method syntax has these parts:

    Part Description
    object Required. Always the name of a FileSystemObject.
    source Required. The path to the folder or folders to be moved. The source argument string can contain wildcard characters in the last path component only.
    destination Required. The path where the folder or folders are to be moved. The destination argument can’t contain wildcard characters.

    Remarks

    If source contains wildcards or destination ends with a path separator (), it is assumed that destination specifies an existing folder in which to move the matching files. Otherwise, destination is assumed to be the name of a destination folder to create. In either case, three things can happen when an individual folder is moved:

    If destination does not exist, the folder gets moved. This is the usual case.

    If destination is an existing file, an error occurs.

    If destination is a directory, an error occurs.
    An error also occurs if a wildcard character that is used in source doesn’t match any folders. The MoveFolder method stops on the first error it encounters. No attempt is made to roll back any changes made before the error occurs.

    Important This method allows moving folders between volumes only if supported by the operating system.

    i ran a simple test movefolder only worked on the same drive

    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • Permission Denied Run-time Error 70 trying to move folder with File System Object


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

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

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 –

Enable the Authorization Checking

  • 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 –

Enable the DCOM (Distributed COM)

  • 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 or Restore the Registry

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.

Понравилась статья? Поделить с друзьями:
  • Video tdr failure amdkmdag sys windows 10 как исправить
  • Visual basic runtime error 5981
  • Visual basic run time error 76 path not found
  • Visual basic on error goto
  • Visual basic error 400