Workbook open vba ошибка

Столкнулся со следующей проблемой, необходимо собрать информацию примерно с 1500 файлов.

Работает частично, так как есть около 100 файлов которые не открываются.
Ошибка на строку :

Код
For i = 1 to 1500
Set x = Workbooks.Open(Thisworkbook.Path & "" & i  & ".xlsx") Ошибка Run-time error '1004'. Method 'Open' of object 'Workbooks' failed
....
Next

Пути и названия файлов корректные.
Файлы по которым ошибка при открытии их вручную выдают сообщение:
«В книге обнаружено содержимое, которое не удалось прочитать.Попробовать восстановить содержимое книги, Если вы доверяете источнику этой книги, нажмите кнопку Да».
В ручную открываются, через VBA — нет.

Можно как то решить проблему открытия таких файлов?
Заранее спасибо.

OK, so far I’ve uninstalled & re installed Office-2010 3 to 4 times, done hours of research for 3 days with no success. I started getting this error either from Vbscript or Excel VBA, performing the same command that has worked for months. I am not sure what I may have changed, I don’t recall changing anything that could cause it but I nailed it down to the ReadOnly:=True parameter. I think something may be wrong with the registry… but re-installing should fix it right? It didn’t…

Anyways, very simple command that I recorded on Excel 2010. This command WORKS FINE and the file opens:

Sub Macro1()
     Workbooks.Open Filename:="C:tempfile_9928_131101.xlsx"
End Sub

But when I add the ReadOnly:=True parameter, it does NOT WORK:

Sub Macro1()
     Workbooks.Open Filename:="C:tempfile_9928_131101.xlsx", ReadOnly:=True
End Sub

This is the returned error Run-time error ‘1004’ Method ‘Open’ of object ‘Workbooks’ failed:

When I click Debug, the error is at the only line of code.

I’ve had this problem (I’m using Microsoft 365), and I found this thread.

It happens for me sometimes when I have another workbook already open, then, on trying to open my macro-enabled workbook, before any sheet is displayed I get the Microsoft warning message about macros. Then, although I click its ‘Enable’ button, the Workbook opens, macros do get enabled, but Workbook_Open doesn’t run.

I’ve never known the problem to occur if no other workbook is open. (Of course, the user might still get the yellow-backed messages at the top of the workbook, asking them to click the Enable Editing and/or Enable Macros buttons.)

Note that my Workbook_Open just calls another ‘workbook-opening’ sub in a module to do all the opening processing.

My solution: When my workbook-opening sub is called, it sets a global variable to True to indicate it has run.

I’ve made it obvious to the user that the problem has occurred, by means of a ‘Welcome’ sheet with all its cells locked, so the user can do nothing; at this point all other sheets are very hidden. The workbook-opening sub, when it runs, deactivates this sheet and makes it very hidden, so the user never normally sees it, and makes the other sheets visible. But if this screen remains, it instructs the user to select the other workbook, then select this one again. My Workbook_Activate code then runs, and because the global variable isn’t True, it calls the workbook-opening sub. If this global variable is True, it does nothing.

To make this work, the Workbook_Close sub makes the other sheets very hidden and the Welcome sheet visible, ready for the next time the Workbook is opened.

Hey presto, the problem is solved.

The Welcome sheet actually has a dual purpose, in that if either of the yellow-backed warning messages are displayed, it will remain and force the user, with suitable instructions, to click Enable Editing and/or Enable macros. If the users aren’t au fait with macro-enabled Excel, they will just ignore these and try to carry on regardless.

All this is much easier to implement than to explain. I hope it’s clear.

And I hope this might be of help to someone.

This is one of the most common run-time errors. By the end of this article, you will understand why that is and how to fix it. A run-time error is the type of error that occurs during the execution of the code. VBA does not know about it prior to actually running the code. There are different variations of this error; we will provide an example of each of the types below.

EXAMPLE 1: VBA Runtime Error 1004: Method ‘Range’ of object ‘_ Global’ failed

When a range reference is not correct. It could be incorrect because it’s misspelled. It could also be incorrect because it’s trying to get a range that is at an impossible value, such as row 0 or row -2. In the example below, we’re referring to row zero and we’re using the wrong syntax. VBA recognizes that we’re trying to refer to a range but it sees that the arguments (parameters) written within the range in order to identify it are written incorrectly; there should be no commas when using Range().

Sub Range_Error()
Range(0, 1).Select
End Sub

range of object global failed

Instead, we should write the code as follows:

Sub Range_Error()
Range(“A1”).Select
End Sub

We could also run into this problem unintentionally if we are looping a variable, such as X, and it becomes zero.

In the below example, X is equal to 5 and the loop is set to keep reducing X by 1 until it reaches -1 then it would not execute. But an error will occur when X = 0.

I set the code to write ‘Correct’ in each of the cells up until the cell we are not able to insert values into. Our code will insert ‘Correct’ in Range(“A5) to Range(“A1”) then will give the error when we ask it to insert ‘Correct’ into Range(“A0”).

Note that we didn’t define X to be a String, so VBA assumes it’s a variant. This means it can be any type of data, so Excel assumes that it’s the type of data that should be utilized in the context we’re utilizing it in. In this case, X would be considered a string. But when X is zero, Excel doesn’t know that it should be string, since “A0” doesn’t exist as a range. So it treats the zero as a number, which triggers this error, because it’s syntax related, meaning what’s written inside Range() is not written correctly from a syntax point of view.

Sub Range_Error()
X = 5
Do Until X = -1
Range("A" & X) = "Correct"
X = X - 1
Loop
End Sub

method range of object global failed

To correct the problem, we need to stop our code from running the loop once X reaches 0.

Sub Range_Error()
X = 5
Do Until X = 0
Range("A" & X) = "Correct"
X = X - 1
Loop
End Sub

EXAMPLE 2: VBA Run Time Error 1004: That Name is already taken. Try a different One

This error is shown when we are trying to give the same name to a worksheet which has already been given to another worksheet in the same workbook. Given that we already have a sheet named “Sheet1”, we create a new sheet, we click on it so that it becomes the active sheet, and we try to name it “Sheet1” by running the below code. We get an error immediately once we reach the sheet name changing line.

Sub Error_Name_Taken()
ThisWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Name = "Sheet1"
End Sub

name already taken

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

This error occurs when we attempt to activate a range through VBA in another worksheet (not the currently active one) without activating that worksheet first.

Sub Error_Select_Failed()
ThisWorkbook.Sheets("Sheet2").Activate
ThisWorkbook.Sheets("Sheet1").Range("A1").Select
End Sub

select method of range class failed

To correct the issue, we would need to first activate “Sheet1” first before attempting to select a range inside of it. Adding a line to active the worksheet resolves the issue.

Sub Error_Select_Failed()
ThisWorkbook.Sheets("Sheet2").Activate
ThisWorkbook.Sheets("Sheet1").Activate
ThisWorkbook.Sheets("Sheet1").Range("A1").Select
End Sub

EXAMPLE 4: VBA Runtime Error 1004: Method ‘Open’ of object ‘Workbooks’ failed

This error occurs when we use VBA to open a workbook that cannot be opened. The reason that Excel is unable to open the workbook could be because it is already open, or the workbook is being used by another program at that moment. A special case exists when you attempt to open a file in read-only mode while the file is corrupt. This would give an error because Excel can open a corrupt file only if it is allowed to repair it first, which it does by writing to it. So, if you open a corrupt file in read-only mode, you are essentially preventing it from repairing the file and hence it would fail to open.

EXAMPLE 5: VBA Runtime Error 1004: file format is not valid

This error, like the one in example 5, is related to attempting to open a file. In this situation, however, we are trying to open a file that isn’t an Excel file; the file doesn’t have any of the Excel extensions ( .xlsx, .xls, .xlsb, .xlsm, etc.)

Sub error_workbook_open()
Workbooks.Open "C:UsersmmostDropboxDaniel TrohaRun-time error 1004.docx"
End Sub

file format is not valid

The code is attempting to open a word document file with extension .docx. Using ‘Workbooks.Open’ can only be used for files that have Excel extensions. To open documents of different extensions, we will need to take a completely different approach. For example, the below code opens a word document.

Sub error_word_doc_open()
Dim wordapp
Dim strFileName As String
strFileName = "C:UsersmmostDropbox Else Without If.docx"
Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open strFile
wordapp.Visible = True
End Sub

EXAMPLE 6: VBA Runtime Error 1004: Sorry We Couldn’t Find:

This error occurs whenever we are trying to open a file that does not exist at the specified path. When faced with this error, it’s important to check three aspects of the file path; file location, file name, and file extension. Any of these parameters could be wrong, so check each of them carefully.

Sub error_workbook_open()
Workbooks.Open "C:UsersmmostDropboxAnother Workbook.xls"
End Sub

couldn't find workbook

EXAMPLE 7: VBA Runtime Error 1004: Application-defined or Object-defined error

This error encompasses a wide range of possibilities. The error is triggered due to violating one of the rules that are used to handle the object you’re working with.

For example, in the following code, I try to select a cell that exists on row -1 and column 1. There is no such cell as the minimum row number allowed is 1, thus, VBA determines that I violated this rule and throws this error.

Note that this is different from Example 1 in that the syntax I am using here is perfectly correct, but I am violating particular rules that once violated, trigger an error. The wide range of these rules make this one of the most common errors in VBA. To resolve it, you will want to know more about the object you’re working with (in this case it’s a cell in the worksheet) and understand the rules and limitations that exist on the various values that you can use with the object.

Sub error_object_defined()
ThisWorkbook.Sheets(1).Cells(-1, 1).Select
End Sub

application defined or object defined error

To wrap it up, here’s one example of where a syntax error calling a function causes this error to occur.

@blink1282 

Object Doesn’t Support this Property or Method

VBA error 438 occurs when you try to use a property or method that does not support by that object. the objects have some properties and methods that you can use but there could be a issue when using a property or method that does not apply to a particular object.

1. You could try disabling all add-ins one by one first to see if it’s causing it from there.

2. Put the code in a module and start the workbook from new so you could see the line where the error occurs.Trace code execution

Otherwise, I recommend uploading/sharing the file (without sensitive data) or displaying the code where it is hanging (performing individual steps and attaching a photo) in order to be able to say more precisely.

Hope I was able to help you with this information.

NikolinoDE

I know I don’t know anything (Socrates)

 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.

LostBY

0 / 0 / 0

Регистрация: 25.04.2013

Сообщений: 12

1

14.01.2016, 18:32. Показов 6443. Ответов 10

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Добрый вечер!

Подскажите, что делаю не так.
Задача: скопировать значение ячейки из одного .xlsm файла в другой. Вот код:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
    Public Function GetFromCloseFile(Data As Range) As Double
    Dim FileName As String
    FileName = "E:Dropbox1. TimeTracking and plansХронометраж" + Data + "_Хронометраж.xlsm"
    
    Dim WB As Workbook
    Set WB = Application.Workbooks.Open(FileName)
   
    GetFromCloseFile = WB.Cells(10, 1) 'WB.Sheets(1).Cells(10, 1).Value
    WB.Close
 
End Function

Дело в том, что WB как был Nothing так и остается Nothing после работы Workbooks.Open. Что делать в такой ситуации?



0



es geht mir gut

11264 / 4746 / 1183

Регистрация: 27.07.2011

Сообщений: 11,438

14.01.2016, 18:36

2

Цитата
Сообщение от LostBY
Посмотреть сообщение

Что делать в такой ситуации?

А строку FileName проверяли? Там правильный адрес файла?



0



0 / 0 / 0

Регистрация: 25.04.2013

Сообщений: 12

14.01.2016, 18:39

 [ТС]

3

Цитата
Сообщение от SoftIce
Посмотреть сообщение

А строку FileName проверяли? Там правильный адрес файла?

Да. Я туда подставлял «C:123.xlsx». Файл 123.xlsx создан



0



es geht mir gut

11264 / 4746 / 1183

Регистрация: 27.07.2011

Сообщений: 11,438

14.01.2016, 18:41

4

Цитата
Сообщение от LostBY
Посмотреть сообщение

Я туда подставлял «C:123.xlsx»

Да это понятно. Я спрашиваю именно про код из первого поста. Строка правильная формируется?



0



0 / 0 / 0

Регистрация: 25.04.2013

Сообщений: 12

14.01.2016, 18:43

 [ТС]

5

Цитата
Сообщение от SoftIce
Посмотреть сообщение

Да это понятно. Я спрашиваю именно про код из первого поста. Строка правильная формируется?

Строка правильная.
Я имею ввиду, что и с «C:123.xlsx» не работает. Файл не открывается



0



es geht mir gut

11264 / 4746 / 1183

Регистрация: 27.07.2011

Сообщений: 11,438

14.01.2016, 18:49

6

Цитата
Сообщение от LostBY
Посмотреть сообщение

Файл не открывается

А должен ли он открываться?
Данная функция возвращает содержимое ячейки А10 указанной книги непонятно какого листа.

Посмотрите хотя бы как называется функция : GetFromCloseFile

Да, и замените + на & , на всякий случай.



0



LostBY

0 / 0 / 0

Регистрация: 25.04.2013

Сообщений: 12

14.01.2016, 19:00

 [ТС]

7

SoftIce, должен открываться. Вот новый код — все равно не работает

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
Public Function GetFromCloseFile(Data As Range) As Double
    Dim FileName As String
    FileName = "E:Dropbox1. TimeTracking and plansÕðîíîìåòðàæ" & Data & "_Õðîíîìåòðàæ.xlsm"
    
    Dim WB As Workbook
    Set WB = Application.Workbooks.Open(FileName)
 
    GetFromCloseFile = WB.Sheets(1).Cells(1, 10)
    WB.Close
 
End Function



0



es geht mir gut

11264 / 4746 / 1183

Регистрация: 27.07.2011

Сообщений: 11,438

14.01.2016, 19:00

8

Вот работа Вашего кода, все четко работает, файл не видно как открывался, а данные получены.
На процедуру main не обращайте внимания, там неправильно объявлена r

Миниатюры

Workbooks.Open не открывает файл
 



0



4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

14.01.2016, 19:02

9

Цитата
Сообщение от LostBY
Посмотреть сообщение

Дело в том, что WB как был Nothing так и остается Nothing после работы Workbooks.Open

Если при попытке открыть несуществующую книгу — не возникает ошибки, значит наличествует инструкция On Error …, которая мешает выявить причину.

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



0



0 / 0 / 0

Регистрация: 25.04.2013

Сообщений: 12

14.01.2016, 19:24

 [ТС]

10

Цитата
Сообщение от pashulka
Посмотреть сообщение

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

Каким?



0



4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

14.01.2016, 19:33

11

LostBY, Если полученное значение — затем вводится в ячейку, то можно сначала ввести обычную ссылку, а затем, заменить формулу на результат, который она возвращает.

Если нет, то A VBA Function To Get A Value From A Closed File



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

14.01.2016, 19:33

11

  • Remove From My Forums
  • Question

  • I am writing a vba macro to open and manipulate a Excel workbook from another Excel workbook. In Excel 2013, the Workbooks.Open does NOT open the called workbook. Even though a watch on the variable shows it is pointing to the correct file, all further watches
    show that the workbook being pointed too is the original workbook. I copied the code into Excel 2010 and it works PERFECTLY. Why is it not working in Excel 2013 but is working in Excel 2010?

    Public Sub add_rows()
    
    Dim xlsheet1 As Excel.Worksheet
    Dim xlsheet2 As Excel.Worksheet
    Dim xlworkbook1 As Excel.Workbook
    Dim xlworkbook2 As Excel.Workbook
    Dim strFileToOpen As Variant
    Dim i As Integer
    
    
    Set xlworkbook1 = ActiveWorkbook
    Set xlsheet1 = xlworkbook1.Worksheets("AddRows")
    
    
    
    strFileToOpen = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", , , , True)
    If TypeName(strFileToOpen) = "Boolean" Then
        MsgBox "No file selected.", vbExclamation, "Sorry!"
        Exit Sub
    Else
        
        For i = LBound(strFileToOpen) To UBound(strFileToOpen)
            xlworkbook1.Activate
            Set xlworkbook2 = Workbooks.Open(strFileToOpen(i))
            xlworkbook2.Activate
            
            Set xlsheet2 = xlworkbook2.Worksheets(1)
            xlsheet2.AutoFilterMode = False
            xlworkbook1.Activate
            xlsheet1.Range("A2:Y9").Copy
            xlworkbook2.Activate
            xlsheet2.Range("A2").Insert Shift:=xlDown
            xlworkbook2.Close (True)
        Next
        
    End If

    • Moved by

      Tuesday, January 26, 2016 7:10 AM
      MOVE CASE

Понравилась статья? Поделить с друзьями:
  • World of tanks снг ошибка
  • World of tanks ошибка подключения к серверу
  • World of tanks ошибка dns
  • World of tanks ошибка dll advapi32 dll
  • World of tanks ошибка 9010