I have a string "sFile" that stores the name of workbook with extension.
I want to activate this workbook, stored in a string.
And then close it.
Code am using is:
Dim wbk as workbook
Set wbk = Workbooks(sFile)
wbk.Activate
wbk.close
But this is not working.Please help.
As mentioned in the comments, it only takes the name (not path) - this should do it for you:
Dim wbk as workbook
Set wbk = Workbooks(right(sFile,Instrrev(sFile,"\")+1))
wbk.Activate
wbk.close
You need to see if you succeed to Set wbk = Workbooks(sFile), it wil work only if the workbook is open.
If it doesn't succeed (wbk Is Nothing), then you need to open the workbook.
Code
Option Explicit
Sub SetWB_toOpenWorkbook()
Dim wbk As Workbook
Dim sFile As String
Dim FilePath As String
' just an example of my file name (clean with extension)
sFile = "SO_1.xlsm"
' set the Dektop path
FilePath = "C:\Users\" & Environ("USERNAME") & "\Desktop\"
On Error Resume Next
Set wbk = Workbooks(sFile)
On Error GoTo 0
If wbk Is Nothing Then ' if not open, then open the workbook
Set wbk = Workbooks.Open(FilePath & sFile)
End If
' just for my tests, put the workbook name in "A1" in "Sheet1"
wbk.Worksheets("Sheet1").Range("A1").Value = wbk.Name
wbk.Activate
wbk.Close True
End Sub
Related
I have two Excel Files in the same folder. The macro runs on the master workbook (wb_master). It should copy the sheet from the Data Workbook (wb_Data) to wb_master.
My attempt is this:
Dim wb_name as String
Dim wb_master as Object
Dim ws_master as Object
Dim wb_Data As Object
Dim MyPath as String
Dim DataFile as String
wb_name = ActiveWorkbook.Name 'other users could have renamed the wb, so I don't want to refer to the name with a fixed string
Set wb_master = Workbooks(wb_name)
Set ws_master = wb_master.Worksheets(1)
MyPath = ActiveWorkbook.Path
DataFile = Dir(MyFolder & "\Data_*.xlsx")
Set wb_Data = Workbooks.Open(FileName:=MyPath & "\" & DataFile)
wb_Data.Sheets(1).Copy After:=wb_master.Sheets(1)
wb_Data.Close SaveChanges:=False
The problem with this is, that in the line where it copies wb_Data.Sheets(1) it doesn't use the wb_master workbook, but the wb_data workbook as destination. I assume this is because when wb_master is called, it reevaluates the ActiveWorkbook, which at this point is wb_Data.
However even though I understand, why this is happening, I can't find a solution to the problem.
Edit: This macro runs in the personal.xslb
Copy Sheet From a Closed Workbook
If you run the code from the Personal.xslb, then replace ThisWorkbook with ActiveWorkbook or the appropriate workbook e.g. Workbooks("Master.xlsm").
Option Explicit
Sub CopySheet()
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Dim FolderPath As String: FolderPath = dwb.Path & "\"
Dim swbName As String: swbName = Dir(FolderPath & "Data_*.xlsx")
If Len(swbName) = 0 Then Exit Sub ' file not found
Dim sFilePath As String: sFilePath = FolderPath & swbName
Dim swb As Workbook: Set swb = Workbooks.Open(sFilePath)
Dim ssh As Object: Set ssh = swb.Sheets(1)
ssh.Copy After:=dwb.Sheets(1) ' second sheet
'ssh.Copy Before:=dwb.Sheets(1) ' first sheet
'ssh.Copy After:=dwb.Sheets(dwb.Sheets.Count) ' last sheet
swb.Close SaveChanges:=False
MsgBox "Sheet copied.", vbInformation
End Sub
in my code I want to prompt the user for a custom workbook name and then saving said workbook on the desktop. For some reason I am getting a Run time error 9 - Subscript out of range when I try to set my workbook to the FilePath. I did some sleuthing around on other posts and I am unsure why I am still getting the error. Is there a better way to do it than mine/ where is my mistake?
Dim WB As Workbook
Dim WS As Worksheet
Dim WorkbookName As String
Dim FilePath As String
WorkbookName = InputBox("What Do you Want to Name the New Workbook?")
FilePath = "C:\Users\JoeK\Desktop\" & WorkbookName & ".xlsx"
'error is at the line below
Set WB = Workbooks(FilePath)
Set WS = Sheets("Sheet1")
Sub CreateEmptyWorkbook()
Dim wb As Workbook
Dim ws As Worksheet
Dim workbookName As String
Dim filePath As String
workbookName = "test"
filePath = GetDesktopPath & workbookName & ".xlsx"
Set wb = Workbooks.Add
wb.SaveAs filePath
wb.Close False
End Sub
Public Function GetDesktopPath() As String
GetDesktopPath = CreateObject("WScript.Shell").specialfolders("Desktop") & "\"
End Function
Set wb = Workbooks.Add - adds the workbook, thus it is empty;
wb.SaveAs filePath - saves it to the filePath, which is the one on the Desktop;
wb.Close False - closing it is needed as well, the False argument is for saving changes. As far as nothing is done in the workbook, this arg it could be True as well;
I have 8 workbooks all with one sheet and I'm trying to import them into one master workbook using VBA. This is the code I'm using, it's my first time using VBA.
Sub ImportStats()
Dim WbDest As Workbook
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim myPath As String
Dim strFileName As String
myPath = ThisWorkbook.path & "\stats\"
Set weDest = ThisWorkbook
strFileName = Dir(myPath)
Do Until strFileName = ""
Set wbSource = Workbooks.Open(Filename:=myPath & "\" & strFileName)
Set wsSource = wbSource.Worksheets(1)
wsSource.Copy after:=WbDest.Worksheets("National2")
wbSource.Close
strFileName = Dir()
Loop
End Sub
Looping Through Files Using Dir
Multiple Issues
'*** is indicating modifications of your code.
Although Dir would accept ThisWorkbook.Path & "\stats\", ThisWorkbook.Path & "\stats" (without the trailing backslash) is sufficient, which will also prevent having a double backslash (wrong) when later building the path with myPath & "\" & strFileName) (indicated in chris neilsen's comment).
Set weDest = ThisWorkbook contains a typo and should be Set wbDest = ThisWorkbook. Using Option Explicit at the beginning of each module, will force you to declare all variables and will 'find' these typos immediately.
In the line CurrentIndex = WbDest.Sheets("National2").Index, we are defining the position of the sheet in the tabs. When using the After argument, then when we add a sheet its index will be by one (1) greater than the index of the specified sheet. When we add another one, its index should be by one (1) greater than the previous one (by two (2) greater than the index of the specified sheet)... hence: CurrentIndex = CurrentIndex + 1.
With SaveChanges:=False in wbSource.Close SaveChanges:=False we are preventing Excel to show us a message (when the worksheet was somehow modified (recalculated)), to ask if the workbook should be saved before closing.
The Code
Option Explicit
Sub ImportStats()
Dim WbDest As Workbook
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim myPath As String
Dim strFileName As String
Dim CurrentIndex As Long '***
myPath = ThisWorkbook.Path & "\stats" '***
Set WbDest = ThisWorkbook '***
CurrentIndex = WbDest.Sheets("National2").Index '***
strFileName = Dir(myPath)
Do Until strFileName = ""
Set wbSource = Workbooks.Open(Filename:=myPath & "\" & strFileName)
Set wsSource = wbSource.Worksheets(1)
wsSource.Copy After:=WbDest.Sheets(CurrentIndex) '***
wbSource.Close SaveChanges:=False '***
CurrentIndex = CurentIndex + 1 ' ***
strFileName = Dir()
Loop
End Sub
As the title suggests, this code fails on the line Sheet.Copy After:=ThisWorkbook.Sheets(1) with runtime error 1004
Why would this run when added as a module but not when saved as an add-in?
Here's the code:
Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Application.ScreenUpdating = False
FolderPath = GetFolder() & "\"
Filename = Dir(FolderPath & "*.xls*")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
Application.ScreenUpdating = True
End Sub
As #BruceWayne suggested is a problem with deciding the correct workbook. As an AddIn, ThisWorkbook will be the AddIn workbook, while ActiveWorkbook (before opening others), will be the workbook you are running your AddIn into.
Simply replacing Thisworkbook with ActiveWorkbook in your scenario won't work, because you would just copy the sheets from the newly open workbook, to the same.
Is a good idea to declare variables to hold this informations, then you can open as many workbooks as you want, and from where you want.
See below:
Application.ScreenUpdating = False
Dim wbDst As Workbook: Set wbDst = ActiveWorkbook 'Can also use Worbooks("book name here")
Dim wbSrc As Workbook
Dim Sht As Worksheet
Dim FolderPath As String: FolderPath = GetFolder() & "\"
Dim FileName As String: FileName = Dir(FolderPath & "*.xls*")
Do While FileName <> ""
Set wbSrc = Workbooks.Open(FileName:=FolderPath & FileName, ReadOnly:=True)
For Each Sht In wbSrc.Worksheets
Sht.Copy After:=wbDst.Sheets(1)
Next Sht
wbSrc.Close
FileName = Dir()
Loop
Application.ScreenUpdating = True
Sub values_dump()
Dim sourceWB As Workbook
Dim destWB As Workbook
Dim ws As Worksheet
Dim path As String
Dim fname As String
Application.ScreenUpdating = False
path = ThisWorkbook.path & "\_bck\"
fname = "values_" & Format(Now, "dd_mmm_yy_hh_mm_ss") & ".xlsm"
Set sourceWB = ThisWorkbook
Set destWB = Workbooks.Add
destWB.SaveAs path & fname
For Each ws In sourceWB.Worksheets
Workbooks(sourceWB).Sheets(ws).Copy after:=Workbooks(destWB).Sheets(1)
Next ws
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
I am getting an error on this line destWB.SaveAs path & fname - it says that I cannot use the ".xlsm" extension ?
In addition I would like to copy the sheets to the new workbook but only retain the values and original formatting.
My code, erroneously copies all the formulae. I do not want to destruct in any way the original workbook.
You are arbitrarily tacking on a Macro-Enabled Workbook file extension (e.g. xlsm) but using Workbook.SaveAs method with the default FileFormat paramter (found in Excel Options ► Save ► Save files in this format:. In fact, it would be better to leave off the .xlsm altogether and specify the desired file format. Excel will add .xlsm if you pick the correct format. See xlFileFormat enumeration for a full list of available SaveAs file types.
If you want to revert the formulas to their values, simply make a copy of the worksheet then use .Cells = .Cells.Value.
Sub values_dump()
Dim sourceWB As Workbook
Dim destWB As Workbook
Dim ws As Worksheet
Dim path As String
Dim fname As String
Dim c As long
Application.ScreenUpdating = False
path = ThisWorkbook.path & "\_bck\"
fname = "values_" & Format(Now, "dd_mmm_yy_hh_mm_ss") & ".xlsm"
Set sourceWB = ThisWorkbook
Set destWB = Workbooks.Add
destWB.SaveAs Filename:=path & fname, FileFormat:=xlOpenXMLWorkbookMacroEnabled 'Open XML Workbook Macro Enabled (52)
For Each ws In sourceWB.Worksheets
if ws.autofiltermode then ws.autofiltermode = false
ws.Copy after:=destWB.Sheets(1)
With destWB.Sheets(2).usedrange
for c = 1 to .columns.count
.columns(c).Cells = .columns(c).Cells.Value
next c
End With
destWB.save
Next ws
Application.ScreenUpdating = True
End Sub
When you Set a workbook-type var to a Workbook Object, you can use the var directly. You seemed to be using it like it was the Workbook.Name property. The same goes for the Worksheet Object and the Worksheet .Name property.