Workbooks.Open Method in VBA - vba

My vba script in myMacro.xls Workbooks.Open Method work well as below,
Workbooks.Open Filename:="D:\ExcelMacroProj\myTest.xls", ReadOnly:=True
But when I try to change the Filename value to a new path as below, but all my practices didn't work. Show Run time error 1004.
Workbooks.Open Filename:="myTest.xls", ReadOnly:=True
or
Workbooks.Open Filename:="./myTest.xls", ReadOnly:=True
or
Workbooks.Open Filename:=".\myTest.xls", ReadOnly:=True
Actually myMacro.xls and myTest.xls was placed in the same folder. That's why I want to change to a flexible folder directory.
how could I fix this issue? Appreciated for your read and reply.

You might try using ThisWorkbook.Path to make an absolute path. It returns the folder path of the workbook running the macro (excluding the filename). Something like this should work:
Workbooks.Open Filename:=ThisWorkbook.Path & "\myTest.xls", ReadOnly:=True
Make sure to include a backslash, since the workbook path doesn't end with one.

Filename is relative to the current Excel directory (which is different from the directory in which an opened document is).
You change the current directory by using ChDir "x:\new\path".
But what you actually want to do is:
Workbooks.Open Filename:=EnsureSlash(ThisWorkbook.Path) & "myTest.xls", ReadOnly:=True
, where EnsureSlash is your custom function that appends a backslash (\) to the end of the string, if it's not already there (because ThisWorkbook.Path ends with a slash when the path is the root directory, and doesn't otherwise).

Related

Save Excel table in current folder

I want to save my current table as a text file in the same folder as the current workbook (that is open).
I use this code:
ActiveWorkbook.SaveAs ThisWorkbook.path & "\" & filename
For some reason it save the text file in the same folder as my personal.xlsb.
I use Office 2010
If this is not possible to do easily then maybe one can force Excel to open a browse window where I can pick where I want the file saved.
ThisWorkbook points to the location where the code is written. In your case personal.xlsb.
If you want to save the table in the same directory as the active workbook, use ActiveWorkbook.path instead.
You may try this
ChDir "C:\yourfolder"
ActiveWorkbook.SaveAs Filename:= _
"c:\yourfolder" & filename & ".txt", FileFormat:=xlText, _
In this example I have created a folder name "yourfolder" in my C drive. The created text file will save in C\yourfolder\filenane.txt
Hope this is helpful

Read a path to a folder from a Excel-Workbook cell using vba

I have the following VBA-code
Dim directory As String, fileName As String
directory = "C:\User\Work\scorix\test_excel\"
fileName = Dir(directory & "*.xl??")
now I would like to change the code so that I would be able to read the path from a given Excel-Workbook cell and then build the fileName.
If I try
directory = Worksheets("Summary").Range("B2").Value
fileName = Dir(directory & "*.xl??")
it dose not work. It means at the end of day directory is empty and therefore fileName is empty.
In the next step I tried
With ThisWorkbook
directory = Sheets("Summary").Range("B2").Value
End With
it works! (But, why?, probably I did not understand the definition of With)
However, in the next step
fileName = Dir(directory & "*.xl??")
filename is still empty. I tried everything with ActiveSheet however, without success!
seems to me those errors occur rather arbitrary, which in my experience can happen when working with several worksheets simultaniously. Maybe replacing
directory = Worksheets("Summary").Range("B2").Value
with
directory = ThisWorkbook.Worksheets("Summary").Range("B2").Value
or alternatively (what is what i prefer to working with a range)
directory = ThisWorkbook.Worksheets("Summary").Cells(2, 2).Value
or alternatively
With ThisWorkbook
' notice the dot in Front of "worksheets"
directory = .Worksheets("Summary").Range("B2").Value
End With
fixes things.
Another situational approach might be to name your Sheet-objects in the VBA-Editor (edit the (Name) property in the property window).
Hope that helps.
P.S.
Since you use the Dir()-Function, I trust you know that in order to get the 2nd+ File, you have to call it repeatedly (maybe in a loop) without supplying a directory.
dir returns the first file in the path\pattern
to recurse you need to do DIR("") pass an empty string
directory = Worksheets("Summary").Range("B2").Value
fileName = Dir(directory & "*.xl??")
there is nothing wrong with this code u might be writing the name of the worksheet wrong maybe?
With ThisWorkbook
directory = Sheets("Summary").Range("B2").Value
End With
Don't forget about using "." before "sheets" when you are using with statements
fileName = Dir(directory & "*.xl??")
The main reason this code didn't work is propably because there are more than one files that ends with "*.xl??" in that folder

Excel workbook trying to save to network directory when it shouldn't when running macro

I'm trying to get a macro to work where it saves a file a certain format and reopens it to avoid compatibility issues, however, when the macro runs it tries to save to a network directory that is no way specified in the code.
Dim wkbook As String
wkbook = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4) & ".xlsm"
ActiveWorkbook.SaveAs wkbook, FileFormat:=52
ActiveWorkbook.Close
Workbooks.Open Filename:=wkbook
Use ChDir to set the directory.
ChDir("C:\mydirectory")

EXCEL VBA: opening XLSM excel using vba

i cant figure out my error in my codes
If cboUnit.Text = "MARINER" Then
Application.ScreenUpdating = False
Application.Workbooks.Open Filename:=ThisWorkbook.Path & "\UNIT" & "\MARINER"
ThisWorkbook.Activate
Workbooks("TOUKEI DATA REPORT GRAPHING").Close
End If
i just want to open xlsm file which is on the folder unit
but i always got an error:
runtime error '1004'
the file this getting is 'xlsx' extension
If you use something like this, it should at least make debugging simpler. Then substitute the code I've provided with this line:
Application.Workbooks.Open Filename:=ThisWorkbook.Path & "\UNIT" & "\MARINER"
Declare the variables with your other variables. I'm understanding your question to be that "Mariner" is the file name. If it's not, you will need to change the fileNPath.
Dim path As String, fileNPath As String
'add these two values above your code
path = ActiveWorkbook.path
fileNPath = path & "\UNIT\MARINER.xlsm"
Application.Workbooks.Open fileName:=fileNPath 'Change this line
Once you've done this, you can see the values for the file path in debug mode where the version you have won't have a value until the line that isn't working anyway. So this way, you can SEE what is going on before you try to USE it.
note: To have a macro enabled workbook, it must be .xlsm, not .xlsx

Saving an Excel sheet in a current directory with VBA

I have created a sheet in vba Excel. I would like to save it the current directory, but not in absolute path, then, when this is executed somewhere else, there won't be problem.
Can somebody help ?
I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Path to get a relative file path:
Sub SaveToRelativePath()
Dim relativePath As String
relativePath = ThisWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
ActiveWorkbook.SaveAs Filename:=relativePath
End Sub
VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.
MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"
This assumes that the sheet you want to save has never been saved and you want to define the file name in code.
If the Path is omitted the file will be saved automaticaly in the current directory.
Try something like this:
ActiveWorkbook.SaveAs "Filename.xslx"
Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:\property\california\sacramento\workbook.xlsx, use this to move the property to berkley:
workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "\" & "newFileName.xlsx"
Only works if your file structure contains one instance of the text used to replace. YMMV.