Excel VBA requiring file extension for workbook reference in some systems

落花浮王杯 提交于 2020-07-01 06:09:11

问题


I have a simple excel VBA that is referring multiple files and copying information across to a master before processing. While building this on my own system a workbook reference (working perfectly fine) was written as:

Workbooks("key").Sheets("Sheet1").Range("A1:X57").Copy

Here key is a .xlsx file

While using this in another system this does not work and it explicitly requires the file extension in every call.

Workbooks("key.xlsx").Sheets("Sheet1").Range("A1:X57").Copy

It would not be extremely difficult for me to make this change although I wanted to understand why this is happening and can I define an Option (guessing!) that would not require me to do so?

Why is there difference in behaviour across systems while running the same script?

Any help would be much appreciated. For me this seems like VBA having a mind of its own.


回答1:


If the key.xlsx file is saved on both systems, including the file extension when referring to the Workbook objects is the safer option because of Windows hide extensions setting:


The Workbooks Collection Object

If the hide extensions setting is not in effect (meaning that extensions are indeed displayed in Windows), you must include the xls extension when you reference a workbook in the Workbooks collection. For example, if you have open a workbook named Book1.xls, you must use

Workbooks("Book1.xls").Activate

rather than

Workbooks("Book1").Activate

to refer to the Book1 workbook. The second line of code above, without the xls extension, will fail with an error 9, Subscript Out Of Range, because there is no workbook with the name Book1. If the hide extensions setting is effect, you can omit the xls extension and use either of the following lines of code.

Workbooks("Book1").Activate

Workbooks("Book1.xls").Activate

These lines of code assume that you do not have open both an unsaved workbook with the name Book1 and a saved workbook with the name Book1.xls. With the hide extensions setting enabled (so that extensions are hidden in Windows), the two lines of code above are functionally equivalent. As a matter of good programming practice, you should always include the xls extension in a workbook name. This ensures that you reference the correct workbook regardless of the value of the hide extensions property.



More details from cpearson.com for File Extensions And Their Implications In VBA Coding



来源:https://stackoverflow.com/questions/50867819/excel-vba-requiring-file-extension-for-workbook-reference-in-some-systems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!