Excel object workbook failed

 

xseed

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

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

#1

05.08.2016 17:50:04

Добрый день! Есть файл xls2txt с макросом, экспортирующий другой файл xls в текст:

Код
Sub Макрос1()
'
' Макрос1 Макрос
    Workbooks.Open Filename:="C:nnCronthebat!1.xls"
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:="C:nncronthebat!1.txt", FileFormat:= _
        xlUnicodeText, CreateBackup:=False
    ActiveWorkbook.Save
    Application.DisplayAlerts = True
    ActiveWindow.Close False
    Windows("xls2txt.xls").Activate
    Application.Quit
End Sub

при попытке выполнить который выдается это сообщение: Run-time error ‘1004’: Method ‘Saveas’ of object ‘_workbook’ failed

Debug переходит на строку

Код
     ActiveWorkbook.SaveAs Filename:="C:nncronthebat!1.txt", FileFormat:= _
        xlUnicodeText, CreateBackup:=False

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

Прикрепленные файлы

  • 1.zip (18.09 КБ)

Изменено: xseed05.08.2016 18:07:23

 

The_Prist

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

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

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

Тут все просто. Вы пытаетесь сохранить файл, который уже открыт под тем же именем самим Excel. Поэтому VBA и генерирует ошибку — файл занят процессом и не может быть перезаписан. Это недопустимо. Сохраняйте либо в другую папку, либо под другими именем.

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

 

xseed

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

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

#3

05.08.2016 17:59:05

Цитата
The_Prist написал:
Вы пытаетесь сохранить файл, который уже открыт под тем же именем

Я открываю файл xls2txt.xls. Выполняю в нем макрос1. Открывается файл 1.xls, сохраняется как 1.txt. Где тут сохранение под тем же именем? Имя то же. но расширение txt. причем, когда я делал запись макроса, excel спрашивал меня. что файл 1.txt уже существует. заменить? Я согласился, нажав Да.

Изменено: xseed05.08.2016 17:59:30
(ошибка)

 

The_Prist

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

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

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

#4

05.08.2016 18:02:04

Да, проглядел расширение. Сказывается, видимо, пятница :)
Но тем не менее. Файл такой есть и Excel делает запрос на его замену. И незаметно для Вас сначала его удаляет, а потом записывает новый. VBA этого за Вас делать не будет. И ошибка в VBA у Вас явно так же говорит о том, что файл такой уже есть. Поэтому сначала убедитесь, что такого файла нет на диске. Если есть — удаляйте:

Код
If dir("C:nncronthebat!1.txt",16) <> "" then
kill "C:nncronthebat!1.txt" 'удаляем файл, если он есть
end if
ActiveWorkbook.SaveAs Filename:="C:nncronthebat!1.txt", FileFormat:=xlUnicodeText, CreateBackup:=False

P.S. Оформляйте код соответствующим тегом(<…>), а не шрифтом. Так нагляднее будет.

Изменено: The_Prist05.08.2016 18:02:36

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

 

xseed

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

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

The_Prist

, нет, файл 1.txt тут ни причем. Если вы выполните мой макрос с обычным xls файлом, никаких ошибок не возникнет, файл сохранится как txt, даже если он существует. Проблема возникнет, только если выполнить макрос с прикрепленным файлом 1.xls (причем его надо поместить в каталог C:nnCronthebat!)

PS: прикрепил файл с макросом xls2txt.xls

Изменено: xseed05.08.2016 18:12:04

 

The_Prist

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

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

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

Пароль к проекту какой? Может там еще какое событие срабатывает.

Изменено: The_Prist05.08.2016 18:17:59

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

 

xseed

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

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

Это не мой файл, пароля не знаю.
Может быть, потому, что в 1.xls установлен VBAProject Password, макрос в файле xls2txt не отрабатывает?
Тогда экспорт вручную в txt на этом файле 1.xls почему тогда работает?

Изменено: xseed05.08.2016 18:29:52

 

xseed

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

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

А можно тогда, если уж макрос не получается выполнить на запаролленом файле, не выполнять его вообще? То есть, можно ли предварительно перед выполнением макроса проверить файл на защиту и если она установлена — не выполнять макрос? Как это сделать?

Изменено: xseed05.08.2016 18:33:47

 

The_Prist

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

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

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

#9

05.08.2016 18:32:39

Тогда сделайте так:

Код
Sub Макрос1()
'
' Макрос1 Макрос
'

'
    Workbooks.Open Filename:="C:nnCronthebat!1.xls"
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    ActiveWorkbook.Sheets(1).Copy
    ActiveWorkbook.SaveAs Filename:="C:nncronthebat!1.txt", FileFormat:= _
        xlUnicodeText, CreateBackup:=False
    ActiveWorkbook.Save
    Application.DisplayAlerts = True
    ActiveWindow.Close False
    Windows("xls2txt.xls").Activate
    Application.Quit
End Sub

больше одного листа все равно не сохраните в txt

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

 

xseed

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

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

#10

05.08.2016 18:40:31

Цитата
The_Prist написал:
ActiveWorkbook.Sheets(1).Copy

Спасибо!
А как работает эта команда? Просто копирует лист или же копирует книгу? Тогда в чем причина проблемы?

Изменено: xseed05.08.2016 18:40:53

 

The_Prist

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

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

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

#11

05.08.2016 18:44:31

Эта команда копирует один(в данном случае первый) лист в новую книгу. Книга создается автоматически.
В чем проблема? В том, что есть пароль на проект. А файл Вы кодом сохраняете без этого самого проекта. И т.к. там есть пароль на проект VBA — то доступа к проекту извне нет для его модификации. А удаление — та еще модификация. Т.е. по факту Вы не можете сохранить данный файл в любом формате, который не поддерживает хранение VBA проекта. А при копировании листа создается новая книга с одним лишь листом и без всяких проектов и защиты.

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

Hello,

     I have code designed to create an archive of my main sheet (as a .xlsx) by copying the sheet > saving the copied sheet in a new workbook > doing things to the sheet within the new workbook > saving and closing new workbook then continuing the rest of my code. 

     Everything works as coded except when the user selects (or keeps selected) the same file location, in the SaveAs dialog, that the original file (with the running VBA) is in. It returns a «Method ‘SaveAs’ of object ‘_Workbook’ failed» error.

     I created an «If» check to see if the selected file location from the SaveAs dialog is the same as the file location of the original and was able to create an error handler (avoid the error), but not an error solution. I want to default to the same file location as the original, and regardless I want the user to be able to save into the same file location, especially since that is a very typical thing to do.

     Line (59) with error 1004:

ActiveWorkbook.SaveAs fileName:=PathAndFile_Name, FileFormat:=xlOpenXMLWorkbook

     ShiftYear (what code is in) and PleaseWait are userforms, and «Troop to Task — Tracker» is the sheet I’m copying.

Code with error:

'<PREVIOUS CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>

'''Declare variables:
'General:
Dim NewGenYear As Integer, LastGenYear As Integer, year_create_counter As Integer
NewGenYear = 0: LastGenYear = 0: year_create_counter = 0
'Personnel:
Dim cell_person As Range, cell_num As Range
Dim cell_num_default As Range
'Archive:
Dim Sheet_Archive As Worksheet, ShVal As Integer
Dim ObFD As FileDialog
Dim File_Name As String
Dim PathAndFile_Name As String
Dim Shape_Clr As Shape
Dim cell_color_convert As Range

'<A WHOLE BUNCH OF OTHER CHECKS AND CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>

'Set then launch SaveAs dialog:
If ShiftYear.CheckBox5.Value = True Then 'Archive <=5 year(s) data externally - Checked:
    For Each Sheet_Archive In ThisWorkbook.Sheets
    Select Case Sheet_Archive.CodeName
    Case Is = "Sheet4", "Sheet5", "Sheet6", "Sheet7"
    ShVal = Sheet_Archive.Name
    If Sheet_Archive.Range("A2").Value <> "N/A" And ShVal <> ShiftYear.Shift_3.Value Then
    File_Name = "Archive " & Sheet_Archive.Name & "_" & ThisWorkbook.Name 'Set default (suggested) File Name
    Set ObFD = Application.FileDialog(msoFileDialogSaveAs)
    With ObFD
        .Title = "Archive Year(s) - Personnel Tracker"
        .ButtonName = "A&rchive"
        .InitialFileName = ThisWorkbook.Path & "" & File_Name 'Default file location and File Name
        .FilterIndex = 1 'File Type (.xlsx)
        .AllowMultiSelect = False
        .InitialView = msoFileDialogViewDetails
        .Show
        If .SelectedItems.count = 0 Then
        MsgBox "Generation and archiving canceled. No year(s) were created, shifted, or overwritten. To continue generating without archiving, uncheck the ""Archive <=5 year(s) calendar/personnel data externally before overwriting"" box then click ""Generate"" again." _
        , vbExclamation, "Year Shift & Creation - Personnel Tracker"
        '<MY CODE THAT TURNS OFF MACRO ENHANCEMENT>
        Exit Sub
        Else
        PathAndFile_Name = .SelectedItems(1)
        End If
    End With
    Application.DisplayAlerts = False
    
'Load year to be archived:
    Worksheets("Formula & Code Data").Range("I7").Value = Sheet_Archive.Name
    Worksheets("Formula & Code Data").Range("I13").Value = "No"
    Call Load_Year.Load_Year

'Copy Troop to Task - Tracker sheet into new workbook and format:
    PleaseWait.Label2.Caption = "Creating " & Sheet_Archive.Name & " archive file ..."
    DoEvents
    File_Name = Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, "")) 'Update File Name to user's input
    ThisWorkbook.Sheets("Troop to Task - Tracker").Copy

    ActiveWorkbook.SaveAs fileName:=PathAndFile_Name, FileFormat:=xlOpenXMLWorkbook 'New workbook save and activate

    '<ALL MY CODE THAT CHANGES THE NEW WORKBOOK>

    Excel.Workbooks(File_Name).Activate
    Excel.Workbooks(File_Name).Close savechanges:=True 'New workbook save and close
    Application.DisplayAlerts = True
    End If
    End Select
    If (Sheet_Archive.CodeName = "Sheet4" Or Sheet_Archive.CodeName = "Sheet5" _
    Or Sheet_Archive.CodeName = "Sheet6" Or Sheet_Archive.CodeName = "Sheet7") _
    And ShVal <> ShiftYear.Shift_3.Value Then
    PleaseWait.Label2.Caption = "" & Sheet_Archive.Name & " archive file complete"
    DoEvents
    Else: PleaseWait.Label2.Caption = "Initailizing archive ..."
    DoEvents: End If
    Next Sheet_Archive
ElseIf ShiftYear.CheckBox5.Value = False Then 'Archive <=5 year(s) data externally - Unchecked:
    'Do Nothing
End If 'Archive <=5 year(s) data externally - END

'<CONTINUING CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>

Code with error handler:

'<PREVIOUS CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>

'''Declare variables:
'General:
Dim NewGenYear As Integer, LastGenYear As Integer, year_create_counter As Integer
NewGenYear = 0: LastGenYear = 0: year_create_counter = 0
'Personnel:
Dim cell_person As Range, cell_num As Range
Dim cell_num_default As Range
'Archive:
Dim Sheet_Archive As Worksheet, ShVal As Integer
Dim ObFD As FileDialog
Dim File_Name As String
Dim PathAndFile_Name As String
Dim Shape_Clr As Shape
Dim cell_color_convert As Range

'<A WHOLE BUNCH OF OTHER CHECKS AND CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>

'Set then launch SaveAs dialog:
If ShiftYear.CheckBox5.Value = True Then 'Archive <=5 year(s) data externally - Checked:
    For Each Sheet_Archive In ThisWorkbook.Sheets
    Select Case Sheet_Archive.CodeName
    Case Is = "Sheet4", "Sheet5", "Sheet6", "Sheet7"
Archive_Error:
    ShVal = Sheet_Archive.Name
    If Sheet_Archive.Range("A2").Value <> "N/A" And ShVal <> ShiftYear.Shift_3.Value Then
    File_Name = "Archive " & Sheet_Archive.Name & "_" & ThisWorkbook.Name 'Set default (suggested) File Name
    Set ObFD = Application.FileDialog(msoFileDialogSaveAs)
    With ObFD
        .Title = "Archive Year(s) - Personnel Tracker"
        .ButtonName = "A&rchive"
        .InitialFileName = ThisWorkbook.Path & "" & File_Name 'Default file location and File Name
        .FilterIndex = 1 'File Type (.xlsx)
        .AllowMultiSelect = False
        .InitialView = msoFileDialogViewDetails
        .Show
        If .SelectedItems.count = 0 Then
        MsgBox "Generation and archiving canceled. No year(s) were created, shifted, or overwritten. To continue generating without archiving, uncheck the ""Archive <=5 year(s) calendar/personnel data externally before overwriting"" box then click ""Generate"" again." _
        , vbExclamation, "Year Shift & Creation - Personnel Tracker"
        '<MY CODE THAT TURNS OFF MACRO ENHANCEMENT>
        Exit Sub
        Else
        PathAndFile_Name = .SelectedItems(1)
        End If
    End With
    Application.DisplayAlerts = False
    
'Load year to be archived:
    Worksheets("Formula & Code Data").Range("I7").Value = Sheet_Archive.Name
    Worksheets("Formula & Code Data").Range("I13").Value = "No"
    Call Load_Year.Load_Year

'Copy Troop to Task - Tracker sheet into new workbook and format:
    PleaseWait.Label2.Caption = "Creating " & Sheet_Archive.Name & " archive file ..."
    DoEvents
    File_Name = Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, "")) 'Update File Name to user's input
    ThisWorkbook.Sheets("Troop to Task - Tracker").Copy
    
    If PathAndFile_Name = ThisWorkbook.Path & "" & File_Name Then 'Error handler
Archive_Error_Actual:
    MsgBox "You cannot save into the same location as this Tracker, in this version. Please select a different file location." _
    , vbExclamation, "Year Shift & Creation - Personnel Tracker"
    'UPDATE MESSAGE AND FIGURE OUT WAY TO FIX RUNTIME ERROR WHEN SAVING TO SAME LOCATION AS THE TRACKER!!!
    ActiveWorkbook.Close savechanges:=False
    GoTo Archive_Error
    End If
    On Error GoTo Archive_Error_Actual
    ActiveWorkbook.SaveAs fileName:=PathAndFile_Name, FileFormat:=xlOpenXMLWorkbook 'New workbook save and activate

    '<ALL MY CODE THAT CHANGES THE NEW WORKBOOK>

    Excel.Workbooks(File_Name).Activate
    Excel.Workbooks(File_Name).Close savechanges:=True 'New workbook save and close
    Application.DisplayAlerts = True
    End If
    End Select
    If (Sheet_Archive.CodeName = "Sheet4" Or Sheet_Archive.CodeName = "Sheet5" _
    Or Sheet_Archive.CodeName = "Sheet6" Or Sheet_Archive.CodeName = "Sheet7") _
    And ShVal <> ShiftYear.Shift_3.Value Then
    PleaseWait.Label2.Caption = "" & Sheet_Archive.Name & " archive file complete"
    DoEvents
    Else: PleaseWait.Label2.Caption = "Initailizing archive ..."
    DoEvents: End If
    Next Sheet_Archive
ElseIf ShiftYear.CheckBox5.Value = False Then 'Archive <=5 year(s) data externally - Unchecked:
    'Do Nothing
End If 'Archive <=5 year(s) data externally - END

'<CONTINUING CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>

Any solution to this is much appreciated!

As Hugo stated, it could be an issue with the mapped drive. I prefer to use the full UNC path (\Thismachine…), in case the workbook gets used on a machine that doesn’t have the mapped drive set up.

I thought the missing extension could be the problem, but I just tested it in Excel 2013 and it automatically added .xlsx to the filename.

The issue is probably due to the wbNew reference. It’s completely unnecessary and should not be combined with ActiveWorkbook. Basically, you should have either a reference to a workbook, or use the predefined ActiveWorkbook reference. I’d also recommend using ThisWorkbook instead, since the user might click on another book while code is running.

Public Sub Copy_Save_R2()
    Dim wbNew As Workbook
    Dim fDate As Date

    fDate = Worksheets("Update").Range("D3").Value

    Application.DisplayAlerts = False
    ThisWorkbook.SaveAs Filename:="Q:R2 Portfolio Prints#Archive - R2 PortfolioR2 Portfolio - CEC A " & Format(fDate, "mm-dd-yyyy") & ".xlsx"
    Application.DisplayAlerts = True

    ThisWorkbook.Sheets("Update").Activate
End Sub

Edit: Added Application.DisplayAlerts commands to prevent any Save popups, such as using .xlsx instead of .xlsm, and overwriting an existing copy.

Edit 2018-08-11: Added escape backslashes to fix UNC path display. Added strike-through to inaccurate statement about the With statement (see comments below). Basically, since nothing between With and End With begins with a ., the statement isn’t doing anything at all.

Содержание

  1. Получение ошибки «метод saveas of object _workbook failed» при попытке сохранить XLSM как CSV
  2. Заметка о гиперссылках
  3. Getting «method saveas of object _workbook failed» error while trying to save an XLSM as CSV
  4. 6 Answers 6
  5. A note on Hyperlinks
  6. ‘Save As’ of object ‘_workbook’ failed
  7. 2 Answers 2
  8. Related
  9. Hot Network Questions
  10. Subscribe to RSS
  11. VBA 1004 Error
  12. VBA Error 1004 in Excel
  13. Top 6 Excel VBA 1004 Runtime Errors
  14. #1 – VBA Run Time Error 1004: That Name is already taken. Try a different One:
  15. #2 – VBA Run Time Error 1004: Method “Range” of object’ _ Global’ failed:
  16. # 3 – VBA Run Time Error 1004: Select Method of Range class failed:
  17. #4 – VBA Runtime Error 1004 method open of object workbooks failed:
  18. #5 – VBA Runtime Error 1004 method Sorry We couldn’t Find:
  19. #6 – VBA Runtime Error 1004 Activate method range class failed:
  20. Recommended Articles

Получение ошибки «метод saveas of object _workbook failed» при попытке сохранить XLSM как CSV

Я пытаюсь сохранить книгу Excel с макросами в виде файла csv, перезаписывая старую (ниже мне пришлось изменить имя папки и листа, но это не проблема).

Иногда это не с

Ошибка выполнения 1004: сбой метода метода объекта _workbook **)

Я погуглил, и некоторые из решений, которые я попробовал, были:

  • Указывая, что каталог является строкой
  • Избегайте каких-либо специальных символов в имени файла или папки (см. Здесь)
  • Скопируйте и вставьте лист в качестве значения перед сохранением его в формате .csv (см. Здесь)
  • Указание FileFormat с кодом .csv (см. Здесь)
  • Отключение/повторное включение некоторых оповещений
  • Добавление других полей в строку ActiveWorkbook.SaveAs, касающихся паролей, создание резервных копий и т.д.

Тем не менее, он может работать правильно до 50-60 раз подряд, а затем в какой-то момент снова произойдет сбой.

Любое предложение, кроме как прекратить использование VBA/Excel для этой задачи, которая скоро произойдет, но пока не могу.

РЕДАКТИРОВАТЬ: Решено благодаря предложению Degustaf. Я внес только два изменения в предложенный Дегустафом код:

  • ThisWorkbook.Sheets вместо CurrentWorkbook.Sheets
  • FileFormat:=6 вместо FileFormat:=xlCSV (очевидно, более устойчив к различным версиям Excel)

Я обычно нахожу, что ActiveWorkbook является проблемой в этих случаях. Под этим я подразумеваю, что каким-то образом у вас не выбрана эта книга (или любая другая), а Excel не знает, что делать. К сожалению, поскольку copy ничего не возвращает (было бы неплохо скопировать лист), это стандартный способ решения этой проблемы.

Таким образом, мы можем подойти к этому как к тому, как мы можем скопировать этот лист в новую рабочую книгу и получить ссылку на эту рабочую книгу. Что мы можем сделать, это создать новую рабочую книгу, а затем скопировать лист:

Или есть еще лучший подход в такой ситуации: WorkSheet поддерживает SaveAs метод. Копия не требуется.

Я предупрежу вас о том, чтобы впоследствии восстановить реальное имя книги, если она остается открытой, но она уже есть в вашем коде.

Это год, но я добавлю что-то для будущих читателей.

Вы не найдете много документации в справочной системе Excel для ошибки времени выполнения 1004, поскольку Microsoft не считает ее ошибкой Excel.

Ответы выше 100% действительны, но иногда это помогает узнать, что вызывает проблему, поэтому вы можете избежать этого, исправить его раньше или исправить его легче.

Тот факт, что это прерывистая ошибка, и фиксируется путем сохранения с полным путем, и имя файла говорит мне, что либо ваш макрос может пытаться сохранить файл .xlsb в каталог автозавершения после автоматического восстановления файлов.

В качестве альтернативы вы можете сами отредактировать путь к файлу или имя файла.

Вы можете проверить путь и имя файла с помощью: –
MsgBox ThisWorkbook.FullName

В окне сообщения вы должны увидеть что-то подобное.

C:UsersMikeAppDataРоумингMicrosoftExcelDIARY (версия 1).xlxb

Если это решение (как указано выше другими), чтобы сохранить файл в правильном пути и имени файла. Это можно сделать с помощью VBA или вручную.

Теперь я привык вручную сохранять файл с правильным путем и именем файла, как само собой разумеющееся после любого действия по автообнаружению, так как он занимает несколько секунд, и я нахожу его быстрее (если это не ежедневное появление). Таким образом, макросы не будут сталкиваться с этой ошибкой, которую вы запускаете. Помните, что, хотя моя привычка вручную сохранять файлы .xlxb в .xlsm файлах сразу после восстановления не поможет новичку, которому вы даете рабочий лист.

После этой ошибки: если у вас есть гиперссылки на рабочем листе, созданные с помощью Ctrl + k , у вас будет что-то вроде “AppDataRoamingMicrosoft ”, “ AppDataRoaming”. /../AppData/Roaming/ “or”….Мои документыМои документы ” в нескольких гиперссылках после восстановления файла. Вы можете избежать этого, добавив свои гиперссылки в текстовое поле или создав их с помощью функции HYPERLINK.

Идентификация и восстановление их немного сложнее

Сначала рассмотрите гиперссылки и определите ошибочные строки и правильную строку для каждой ошибки. Со временем я нашел несколько.

Excel не предоставляет средства в меню “Перейти к специальному” для поиска гиперссылок, созданных с помощью Ctrl + k .

Вы можете автоматизировать идентификацию ошибочных гиперссылок в столбце помощника, например, столбец Z и используя формулу

где Link2Text – это UDF

Функция Link2Text (rng As Range) As String “НЕ деактивируйте. ‘Определяет гиперссылки, содержащие” роуминг” в столбце Z.

Мой VBA для исправления ошибок выглядит следующим образом

‘Выберите правильный лист Листы ( “ДНЕВНИК” ). Выберите

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

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

Следующие ярлыки будут делать резервные копии рабочего листа в секундах: Ctrl + O , [выделить имя файла], Ctrl + C , Ctrl + V , [X]. Обычные резервные копии позволяют сразу перейти к самой последней резервной копии без необходимости восстановления из файла резервной копии прошлой ночью, особенно если вам нужно сделать запрос другого человека, чтобы сделать это.

Источник

Getting «method saveas of object _workbook failed» error while trying to save an XLSM as CSV

I’m trying to save a macro-enabled Excel workbook as a csv file, overwriting the old one (below I had to change the name of the folder and the Sheet, but that doesn’t seem to be the issue).

Sometimes it fails with

Runtime Error 1004: method saveas of object _workbook failed**)

The debugger points out:

I googled and some of the solutions I tried were:

  • Specifiying that the directory is a string
  • Avoid any special character in the file name or folder (seen here)
  • Copy paste the worksheet as value before saving it as .csv (seen here)
  • Specifying the FileFormat with the .csv code number (seen here)
  • Disabling/Re-enabling some of the alerts
  • Adding other fields in the ActiveWorkbook.SaveAs row, regarding passwords, creating backups etcetc

Still, it might run correctly up to 50-60 times in a row, and then at some point fail again.

Any suggestion, except stop using VBA/Excel for this task, which will happen soon, but I can’t for now.

EDIT: Solved thanks to Degustaf suggestion. I made only two changes to Degustaf’s suggested code:

  • ThisWorkbook.Sheets instead of CurrentWorkbook.Sheets
  • FileFormat:=6 instead of FileFormat:=xlCSV (apparently is more robust to different versions of Excel)

6 Answers 6

I generally find that ActiveWorkbook is the problem in these cases. By that I mean that somehow you don’t have that workbook (or any other) selected, and Excel doesn’t know what to do. Unfortunately, since copy doesn’t return anything (the copied worksheet would be nice), this is a standard way of approaching this problem.

So, we can approach this as how can we copy this sheet to a new workbook, and get a reference to that workbook. What we can do is create the new workbook, and then copy the sheet:

Or, there is an even better approach in a situation like this: WorkSheet supports the SaveAs method. No copy necessary.

I will warn you to resave the workbook to its original name afterwards, if it is staying open, but you already have that in your code.

This is a year old, but I’ll add something for future readers

You won’t find a lot of documentation in Excel help for Run-time error 1004 as Microsoft doesn’t consider it to be an Excel error.

The answers above are 100% valid but sometimes it helps to know what is causing the problem so you can avoid it, fix it earlier or fix it more easily.

The fact that this is an intermittent fault, and it is fixed by saving with the full path and file name tells me that either your macro may be trying to save an .xlsb file to the autorecover directory after an auto file recovery.

Alternatively, you may have edited the file’s path or filename yourself.

You can check the path and filename with:- MsgBox ThisWorkbook.FullName

You should see something like this in the message box.

If so the solution is (as stated above by others) to save your file to its correct path and file name. This can be done with VBA or manually.

I am now in the habit of manually saving the file with its correct path and filename as a matter of course after any autorecover action as it takes seconds and I find it quicker (if this is not a daily occurrence). Thus, the macros will not encounter this fault you run it. Remember that while my habit of manually saving .xlxb files to .xlsm files immediately after a recovery won’t help a novice that you give the worksheet to.

A note on Hyperlinks

After this error: If you have hyperlinks in your worksheet created with Ctrl + k in all likelihood, you will have something like «AppDataRoamingMicrosoft», «AppDataRoaming», «../../AppData/Roaming/»or «. My documentsMy documents» in multiple hyperlinks after file recovery. You can avoid these by attaching your hyperlinks to a text box or generating them with the HYPERLINK function.

Identifying and Repairing them is a little more complicated

First, examine the hyperlinks and determine the erroneous strings and the correct string for each error. Over time, I have found several.

Excel doesn’t provide a facility in the ‘Go To Special’ menu to search for hyperlinks created with Ctrl + k .

You can automate the identification of erroneous hyperlinks in a helper column, say column Z and using the formula

where Link2Text is the UDF

Function Link2Text(rng As Range) As String ‘ DO NOT deactivate. ‘ Locates hyperlinks containing ‘roaming’ in column Z.

My VBA to correct the errors is as follows

‘ Select the correct sheet Sheets(«DIARY»).Select

I also recommend you get in the habit of doing regular backups and not relying on autorecover alone. If it fails, you have nothing since your last full backup.

While the worksheet is being fragile backup often, like every hour or after any significant import of new data.

The following shortcuts will backup your worksheet in seconds: Ctrl + O , [highlight the filename], Ctrl + C , Ctrl + V , [ X ]. Regular backups allow you to go immediately to your most recent backup without having to restore from last night’s backup file especially if you have to make a request of another person to do this.

Источник

‘Save As’ of object ‘_workbook’ failed

I am trying to save a workbook as xlsm, this is the code I use:

I have done some testing, and It does in fact save in both a private folder and a public or shared folder however when I save it in a shared folder I also get this:

Run-time error ‘1004’ Method ‘Save As’ of object ‘_workbook’ failed

why do I get error message when it is saved in a public/shared folder, or onedrive?

2 Answers 2

In your string containing path there is variable «path» i suppose. Then you should write it like this:

Or you can hardcode full path (but i recommend using variables — first example).

Then when you can save it manually and you have permissions then i have no idea since i normally save files to shared folders and network drives. Maybe your specific path is wrong. It is best to save using servername and folders.

Because sometimes when you refefer to mapped drive for example X:folder2 then you must ensure that all users have it mapped in same way (someone uses X someone uses R etc.). And if path is correct then only other way i can think of it is permission issue, but if you can save it manually then i have sadly no idea. 🙂

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.20.43331

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

VBA 1004 Error

VBA 1004 Error is a runtime error in VBA. It is also known as application-defined or object-defined error. Why is that? Because we have a limited number of columns in Excel. When our code gives the command to go out of range, we get a 1004 Error. There are other situations when we get this error when we refer to a range that does not exist in the sheet.

VBA Error 1004 in Excel

VBA 1004 Error is a run time error in VBA and occurs while running the code. Errors are part and parcel of the coding, especially when writing for the first time. Therefore, you may come across many errors in VBA. However, this is common for everybody, and there is no big deal about it.

However, knowing the error of why it is coming makes you avoid those mistakes in the coming future.

In this article, we will discuss one of the important errors in Excel, “VBA 1004 Error”.

Table of contents

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA 1004 Error (wallstreetmojo.com)

Top 6 Excel VBA 1004 Runtime Errors

#1 – VBA Run Time Error 1004: That Name is already taken. Try a different One:

This error occurs while renaming the sheet.

If the worksheet’s name already exists. If you try to assign the same name to another sheet, VBA throws a “Run-time error ‘1004.’ ”

Look at the below code.

Code:

We are trying to rename sheet 2 as sheet 1. But, we already have a sheet named “Sheet1”.

If we run this code using the F5 key or manually, we will get “Run-time error ‘1004’ “: “That name is already taken. Try a different one.”

So, try renaming the sheet accordingly.

#2 – VBA Run Time Error 1004: Method “Range” of object’ _ Global’ failed:

For this, we have named the range of cells “Headings,” as shown in the below image.

Now, by using the RANGE object, we can access this range.

Code:

If you run this code by pressing the F5 key, then this code will select the named range.

But, if we mention the named range wrongly, we will get “Run-time error ‘1004.’ “Method “Range” of object’ _ Global” failed.

Code:

Run this code manually or use the F5 key and see the result.

# 3 – VBA Run Time Error 1004: Select Method of Range class failed:

It usually occurs when we try to select the cells other than the active sheet without making the sheet select or active.

Look at the below code.

Code:

The above code says to select the cells A1 to A5 in the worksheet “Sheet1”. However, to experiment, my present active sheet is “Sheet2”, not “Sheet1”.

We will run this code using the F5 key or manually to see what happens.

We got “Run-time error ‘1004.’ “Select method of Range class failed” as without activating the sheet; we try to select the cells of that sheet. So first, we need to activate the sheet before we select the cells. Below is the correct code.

#4 – VBA Runtime Error 1004 method open of object workbooks failed:

It usually occurs when you try to open the workbook, which has the same name as the other workbook we have already opened.

Look at the below code.

Code:

It will throw the below error.

#5 – VBA Runtime Error 1004 method Sorry We couldn’t Find:

This error occurs when you try to open the file which does not exist in the mentioned path. For example, it could move, be renamed, or deleted from the mentioned path. One reason for this is the wrong type of path or file name with the excel extension Excel Extension Excel extensions represent the file format. It helps the user to save different types of excel files in various formats. For instance, .xlsx is used for simple data, and XLSM is used to store the VBA code. read more .

Now, take a look at the below code.

Code:

This code says to open the file “ABC.xlsx” in the mentioned folder path.

We know there is no file in the mentioned folder path. So, we will get the: Run-time error ‘1004’ method when no file exists in the mentioned folder. Sorry, and We couldn’t find it.

#6 – VBA Runtime Error 1004 Activate method range class failed:

This error occurs mainly due to activating the range of cells without activating the worksheet.

Look at the below code.

Code:

This error is similar to the one we have seen in Run-time error’ 1004′: Select method of Range class failed.

If we run manually or use the F5 key, we will get the below error.

Because without activating the sheet, we cannot activate the cells in it. So first, activate the sheet and then activate the cells of that sheet.

Recommended Articles

This article has been a guide to VBA 1004 Error. Here, we discuss the top 6 types of 1004 run-time errors in VBA and how to fix them, along with examples and downloadable templates. Below are some useful articles related to VBA: –

Источник

 Summary:

In this post, I have included the complete information about Excel runtime error 1004. Besides that I have presented some best fixes to resolve runtime error 1004 effortlessly.

To fix Runtime Error 1004 in Excel you can take initiatives like uninstalling Microsoft Work, creating a new Excel template, or deleting The “GWXL97.XLA” File. If you don’t have any idea on how to apply these methods then go through this post.

Here in this article, we are going to discuss different types of VBA runtime error 1004 in Excel along with their fixes.

What Is Runtime Error 1004 In VBA Excel?

Excel error 1004 is one such annoying runtime error that mainly encounters while working with the Excel file. Or while trying to generate a Macro in Excel document and as a result, you are unable to do anything in your workbook.

This error may cause serious trouble while you are working with Visual Basic Applications and can crash your program or your system or in some cases, it freezes for some time. This error is faced by any versions of MS Excel such as Excel 2007/2010/2013/2016/2019 as well.

To recover lost Excel data, we recommend this tool:

This software will prevent Excel workbook data such as BI data, financial reports & other analytical information from corruption and data loss. With this software you can rebuild corrupt Excel files and restore every single visual representation & dataset to its original, intact state in 3 easy steps:

  1. Download Excel File Repair Tool rated Excellent by Softpedia, Softonic & CNET.
  2. Select the corrupt Excel file (XLS, XLSX) & click Repair to initiate the repair process.
  3. Preview the repaired files and click Save File to save the files at desired location.

Error Detail:

Error Code: run-time error 1004

Description: Application or object-defined error

Screenshot Of The Error:

run-time error 1004

Don’t worry you can fix this Microsoft Visual Basic runtime error 1004, just by following the steps mentioned in this post. But before approaching the fixes section catch more information regarding runtime error 1004.

Excel VBA Run Time Error 1004 Along With The Fixes

EXCEL ERRORS

The lists of error messages associated with this Excel error 1004 are:

  1. VB: run-time error ‘1004’: Application-defined or object-defined error
  2. Excel VBA Runtime error 1004 “Select method of Range class failed”
  3. runtime error 1004 method range of object _global failed visual basic
  4. Excel macro “Run-time error ‘1004″
  5. Runtime error 1004 method open of object workbooks failed
  6. Run time error ‘1004’: Method ‘Ranger’ of Object’ Worksheet’ Failed
  7. Save As VBA run time Error 1004: Application defined or object defined error

Let’s discuss each of them one by one…!

#1 – VBA Run Time Error 1004: That Name is already taken. Try a different One

This VBA Run Time Error 1004 in Excel mainly occurs at the time of renaming the sheet.

If a worksheet with the same name already exists but still you are assigning that name to some other worksheet. In that case, VBA will throw the run time error 1004 along with the message: “The Name is Already Taken. Try a different one.”

VBA Run Time Error 1004 in Excel 1

Solution: You can fix this error code by renaming your Excel sheet.

#2 – VBA Run Time Error 1004: Method “Range” of object’ _ Global’ failed

This VBA error code mainly occurs when someone tries to access the object range with wrong spelling or which doesn’t exist in the worksheet.

Suppose, you have named the cells range as “Headings,” but if you incorrectly mention the named range then obviously you will get the Run Time Error 1004: Method “Range” of object’ _ Global’ failed error.

VBA Run Time Error 1004 in Excel 2

Solution: So before running the code properly check the name of the range.

# 3 – VBA Run Time Error 1004: Select Method of Range class failed

This error code occurs when someone tries to choose the cells from a non-active sheet.

 Let’s understand with this an example:

Suppose you have selected cells from A1 to A5 from the Sheet1 worksheet. Whereas, your present active worksheet is Sheet2.

At that time it’s obvious to encounter Run Time Error 1004: Select Method of Range class failed.

VBA Run Time Error 1004 in Excel 3

Solution: To fix this, you need to activate the worksheet before selecting cells of it.

#4 – VBA Runtime Error 1004 method open of object workbooks failed

This specific run time Error 1004 arises when someone tries to open an Excel workbook having the same workbook name that is already open.

In that case, it’s quite common to encounter VBA Runtime Error 1004 method open of object workbooks failed.

VBA Run Time Error 1004 in Excel 4

Solution: Well to fix this, first of all close the already opened documents having a similar name.

#5 – VBA Runtime Error 1004 Method Sorry We Couldn’t Find:

The main reason behind the occurrence of this VBA error in Excel is due to renaming, shifting, or deletion of the mentioned path.

The reason behind this can be the wrong assigned path or file name with extension.

When your assigned code fails to fetch a file within your mentioned folder path. Then you will definitely get the runtime Error 1004 method. Sorry, and We couldn’t find it.

VBA Run Time Error 1004 in Excel 5

Solution: make a proper check across the given path or file name.

#6 – VBA Runtime Error 1004 Activate method range class failed

Behind this error, the reason can be activating the cells range without activating the Excel worksheet.

This specific error is quite very similar to the one which we have already discussed above i.e Run Time Error 1004: Select Method of Range class failed.

VBA Run Time Error 1004 in Excel 6

Solution: To fix this, you need to activate your excel sheet first and then activate the sheet cells. However, it is not possible to activate the cell of a sheet without activating the worksheet.

Why This Visual Basic Runtime Error 1004 Occurs?

Follow the reasons behind getting the run time error 1004:

  1. Due to corruption in the desktop icon for MS Excel.
  2. Conflict with other programs while opening VBA Excel file.
  3. When filtered data is copied and then pasted into MS Office Excel workbook.
  4. Due to application or object-defined error.
  5. A range value is set programmatically with a collection of large strings.

Well, these are common reasons behind getting the VBA runtime error 1004, now know how to fix it. Here we have described both the manual as well as automatic solution to fix the run time error 1004 in Excel 2016 and 2013. In case you are not able to fix the error manually then make use of the automatic MS Excel Repair Tool to fix the error automatically.

Fix Runtime Error 1004

Follow the steps given below to fix Excel run time error 1004 :

1: Uninstall Microsoft Work

2: Create New Excel Template

3: Delete The “GWXL97.XLA” File

Method 1: Uninstall Microsoft Work

1. Go to the Task Manager and stop the entire running programs.

2. Then go to Start menu > and select Control Panel.

run time error 1004 (1)

3. Next, in the Control Panel select Add or Remove Program.

run time error 1004 (2)

4. Here, you will get the list of programs that are currently installed on your PC, and then from the list select Microsoft Work.

run time error 1004

5. And click on uninstall to remove it from the PC.

It is also important to scan your system for viruses or malware, as this corrupts the files and important documents. You can make use of the best antivirus program to remove malware and also get rid of the runtime error 1004.

Method 2: Create New Excel Template

Another very simple method to fix Excel runtime error 1004 is by putting a new Excel worksheet file within a template. Instead of copying or duplicating the existing worksheet.

Here is the complete step on how to perform this task.

1.Start your Excel application.

2. Make a fresh new Excel workbook, after then delete the entire sheets present on it leaving only a single one.

3. Now format the workbook as per your need or like the way you want to design in your default template.

4. Excel 2003 user: Tap to the File>Save As option

SAVE EXCEL FILE

OR Excel 2007 or latest versions: Tap to the Microsoft Office button after then hit the Save As option.

SAVE EXCEL FILE 1

5. Now in the field of File name, assign name for your template.

6. On the side of Save as type there is a small arrow key, make a tap on it. From the opened drop menu

  • Excel 2003 users have to choose the Excel Template (.xlt)

Create New Excel Template 1

  • And Excel 2007 or later version have to choose the Excel Template (.xltx)

Create New Excel Template 2

7. Tap to the Save.

8. After the successful creation of the template, now you can programmatically insert it by making use of the following code:
Add Type:=pathfilename

Remarks: 

From the above code, you have to replace the pathfilename with the complete path including the file name. For assigning the exact location of the sheet template you have just created.

Method 3: Delete The “GWXL97.XLA” File

Follow another manual method to fix Excel Runtime Error 1004:

1. Right-click on the start menu.

2. Then select the Explore option.

Excel Runtime Error 1004

3. Then open the following directory – C:Program FilesMSOfficeOfficeXLSTART

Excel Runtime Error 1004 (1)

4. Here you need to delete “GWXL97.XLA” file

Excel Runtime Error 1004 (2)

5. And open the Excel after closing the explorer

You would find that the program is running fine without a runtime error. But if you are still facing the error then make use of the automatic MS Excel Repair Tool, to fix the error easily.

Automatic Solution: MS Excel Repair Tool

MS Excel Repair Tool is a professional recommended solution to easily repair both .xls and .xlsx file. It supports several files in one repair cycle. It is a unique tool that can repair multiple corrupted Excel files at one time and also recover everything included charts, cell comments, worksheet properties, and other data. This can recover the corrupt Excel file to a new blank file. It is extremely easy to use and supports both Windows as well as Mac operating systems.

* Free version of the product only previews recoverable data.

Steps to Utilize MS Excel Repair Tool:

Conclusion:

Hope this article helps you to repair the runtime error 1004 in Excel and recovers Excel file data. In this article, we have provided a manual as well as automatic solution to get rid of Excel run-time error 1004. You can make use of any solution according to your desire.

Good Luck!!!

Priyanka is an entrepreneur & content marketing expert. She writes tech blogs and has expertise in MS Office, Excel, and other tech subjects. Her distinctive art of presenting tech information in the easy-to-understand language is very impressive. When not writing, she loves unplanned travels.

Like this post? Please share to your friends:
  • Excel object properties and methods
  • Excel object in html
  • Excel object in cell
  • Excel oart dll ошибка
  • Excel numeric to text