I have a workbook that gets created every week that has a variable name structure. The name structure is as follows : Week of Year & Invoice & date. So a sample file might be called 1_Invoice_01052018.xlsm
I have to update the report every week. I want to declare the variable workbook name as a variable in VBA. I have another workbook that contains the output of the report that is created via VBA. In this other workbook I want to be able to call the Invoice spreadsheet but since it has a variable name, I am having issues finding it. So I put together the VBA below.
Sub Test()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = "*Invoice*" & ".xlsm"
Set ws = Sheets("Sheet1")
wb.Activate
ws.Select
End Sub
However, this results in a "Type mismatch" error.
I also tried the following:
Sub Test2()
Windows("*Invoice*" & ".xlsm").Activate
End Sub
This also resulted in an error.
Any ideas on how to set a variable workbook name as a variable in VBA? I would only have one of these workbooks open at a time, so I wouldn't run into any issues
You have to set the workbook correctly:
Sub Test()
Dim wb As Workbook
Dim ws As Worksheet
Dim FilePath As String
FilePath = "C:\" & AnotherVariable & ".xlsx"
Set wb = Workbooks(FilePath)
Set ws = Sheets("Sheet1")
wb.Activate
ws.Select
End Sub
To create a new workbook you'd use Workbooks.Add. To open an existing one you'd use Workbooks.Open and then reference the worksheet within that workbook.
To change the name of the file you'd save it with a new name using the SaveAs method.
Sub Test()
Dim wb As Workbook
Dim ws As Worksheet
Dim FileName As String
Set wb = Workbooks.Add 'Creates a new workbook with default name.
'Set wb = Workbooks.Open("<path to folder>\" & FileName & ".xlsm") 'Open an existing file.
Set ws = wb.Worksheets("Sheet1")
wb.SaveAs "<path to folder>\" & FileName & ".xlsm" 'Save and rename here.
With ws
.Range("A1") = "Adding some text to this cell"
End With
End Sub
As a further example, the code below will create two workbooks before copying the sheet from the first workbook to the end of the second workbook.
Sub Test1()
Dim wb As Workbook, wb1 As Workbook
Dim ws As Worksheet
'Create first workbook so it contains only 1 sheet (xlWBATWorksheet)
', reference Sheet1 and add some data to it.
Set wb = Workbooks.Add(xlWBATWorksheet)
Set ws = wb.Worksheets("Sheet1")
ws.Range("A1") = "This cell populated in first workbook."
'Create second workbook with default number of sheets
'and copy Sheet1 from first book to the end of this one.
Set wb1 = Workbooks.Add
ws.Copy After:=wb1.Sheets(wb1.Sheets.Count)
End Sub
Edit again:
To figure out the workbook name based on WeekNumber_Invoice_Date you could use:
Sub Test2()
Dim wb As Workbook
Dim sPath As String
Dim dDate As Date
dDate = Date 'Todays date
sPath = "C:\MyFolder\"
sPath = sPath & _
WorksheetFunction.WeekNum(dDate, 2) & "_Invoice_" & Format(dDate, "ddmmyyyy") & ".xlsm"
'Open if already exists.
'Set wb = Workbooks.Open(sPath)
'Create and SaveAs new name.
Set wb = Workbooks.Add
wb.SaveAs sPath
End Sub
This would give a file path of C:\MyFolder\43_Invoice_22102018.xlsm based on todays date of 22nd October '18.
Note: The WEEKNUM function considers the week containing January 1 to be the first week of the year.
I was able to get what I need from the following link:
excel-vba-extract-text-between-2-characters
I reviewed the link above and put together the VBA below.
Sub test2()
Dim str As String
Dim openPos As Integer
Dim closePos As Integer
Dim midBit As String
str = Range("b1").Value
openPos = InStr(str, "[")
closePos = InStr(str, "]")
midBit = Mid(str, openPos + 1, closePos - openPos - 1)
'MsgBox (midBit)
Windows(midBit).Activate
End Sub
I ended up creating a dynamic file path in cell B1 that contained a concatenated file path string that contained look ups to pull in the Week of Year and Date based on the Current Date. Since this path is dynamic it will always point to the right path given that I open the Invoice on the correct week. I pulling the file name from the path and opening based on the file name which is dynamic.
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
This script loops through a file pathway and combines all workbooks into a master workbook and sections each workbook into a worksheet within the master file.
I have a line ws.Name = activeworksheet.Range("B1").Value that names the sheets as a copy of the first workbook's worksheet Sheet1 and names every sheet after that like Sheet1(2).
How can this be changed to the value in cell B1 of the workbook it is consolidating into the master workbook?
rest of script:
Option Explicit
Sub CombineWorkbooks()
Dim MainWB As Workbook
Dim sDirPath As String
Dim sFileName As String
Dim sFilePath As String
Dim wb As Workbook
Dim ws As Worksheet
sDirPath = "M:\New folder"
sFileName = Dir(sDirPath & "\*.xlsx")
Set MainWB = ThisWorkbook
Do While Len(sFileName) > 0
sFilePath = sDirPath & "\" & sFileName
Set wb = Workbooks.Open(Filename:=sFilePath)
For Each ws In wb.Sheets
ws.Copy After:=MainWB.Sheets(MainWB.Sheets.Count)
ws.Name = activeworksheet.Range("B1").Value
Next ws
wb.Close SaveChanges:=False
sFileName = Dir
Loop
End Sub
after .Copy() method of Sheet object, the newly created sheet becomes the active one, while ws still holds reference to the original sheet
so go like follows
For Each ws In wb.Sheets
ws.Copy After:=MainWB.Sheets(MainWB.Sheets.Count)
ActiveSheet.Name = ws.Range("B1").Value
Next
When using all the different examples that I've found on stackoverflow they give me a complex task that still requires a mouse click to confirm its ok to paste the data. I also am struggling to get the whole thing to operate in one section of VBA code.
Public Sub copySheets()
Dim wkb As Excel.Workbook
Dim newWkb As Excel.Workbook
Dim wks As Excel.Worksheet
Dim newWks As Excel.Worksheet
Dim sheets As Variant
Dim varName As Variant
'------------------------------------------------------------
'Define the names of worksheets to be copied.
sheets = VBA.Array("Analysis - London", "London - Commercial")
'Create reference to the current Excel workbook and to the destination workbook.
Set wkb = Excel.ThisWorkbook
Set newWkb = Excel.Workbooks.Add
For Each varName In sheets
'Clear reference to the [wks] variable.
Set wks = Nothing
'Check if there is a worksheet with such name.
On Error Resume Next
Set wks = wkb.Worksheets(VBA.CStr(varName))
On Error GoTo 0
'If worksheet with such name is not found, those instructions are skipped.
If Not wks Is Nothing Then
'Copy this worksheet to a new workbook.
Call wks.Copy(newWkb.Worksheets(1))
'Get the reference to the copy of this worksheet and paste
'all its content as values.
Set newWks = newWkb.Worksheets(wks.Name)
With newWks
Call .Cells.Copy
Call .Range("A1").PasteSpecial(Paste:=xlValues)
End With
End If
Next
ActiveWorkbook.SaveCopyAs Filename:=("C:\Users\\My stuff\Forecast" & Format(Now(), "YYYYMMDD") & " Forecasting" & ".xlsm")
Thanks
Replace
With newWks
Call .Cells.Copy
Call .Range("A1").PasteSpecial(Paste:=xlValues)
End With
With
Dim c as range
For each c in newwks.usedrange
c.formula = c.value
next c
I keep getting a 'Method 'SaveAS' of object '_Workbook' failed, I can't for the life of me figure out why. Code below... any recommendation unrelated to the initial question are welcome!
Private Sub CommandButton1_Click()
'Declarations
'The two workbooks to be involved
Dim SourceWB As Workbook
Dim DestinationWB As Workbook
'values to contain cell data to be copied across the worksheet
Dim systemName As Variant
Dim systemID As Variant
'Counter variable to allow for the loop
Dim counter As Integer
'Set the source workbook equal to the current workbook
Set SourceWB = ActiveWorkbook
For counter = 1 To 5
'Set the values for the two data values to be copied
systemName = SourceWB.Sheets("Sheet1").Cells(counter, 1).Value
systemID = SourceWB.Sheets("Sheet1").Cells(counter, 2).Value
'Open the destination Workbook
Set DestinationWB = Workbooks.Open("Path to workbook")
'Set destination cells equal to the copied data from the source sheet
DestinationWB.Sheets("Questionnaire").Cells(7, 3).Value = systemName
DestinationWB.Sheets("Questionnaire").Cells(8, 3).Value = systemID
'Set fname to save Destination Workbook
Fname = "H:\Desktop\Automated Questionnaires to send\" & systemName & " Applicability Questionnaire.xlsm"
'Save the Destination workbook
DestinationWB.SaveAs Filename:=Fname, FileFormat:=52
DestinationWB.Close
Next counter
End Sub
I have a sheet Rolling Plan in copy.xls worksheet.I want to copy it to Book1.xls worksheet in Sheet NO1 in Range A1:H6
The macro in Book.xls
Sub CopytoPS()
Dim sfil As String
Dim owbk As Workbook
Dim sPath As String
sPath = "C:\Users\Nirmala\Desktop\website" 'Change the file path for your purposes
sfil = Dir(sPath & "copy.xls")
Range("B6:H6").Copy
Set owbk = Workbooks.Open(sPath & sfil)
owbk.Sheets("RollinPlan").Range("B6:H6").End(xlUp).Offset(1, 0).
PasteSpecial xlPasteValues
owbk.Close True 'Save opened workbook and close
sfil = Dir
End Sub
This does the following:
1) Open copy.xls and copy data in range B6:H6
2) Pastes the data into workbook Book1 in range A1:H6 on sheet NO1
Sub CopyData()
Dim filePath As String, wb As Workbook
filePath = "C:\Users\Nirmala\Desktop\website" 'Change the file path for your purposes
Set wb = Workbooks.Open(Filename:=filePath & "\" & "copy.xls")
wb.Worksheets("Rolling Plan").Range("B6:H6").Copy Destination:=ThisWorkbook.Worksheets("NO1").Range("A1:H6")
wb.Close
End Sub
Note that I am not quite sure why the data range you are copying to (i.e. A1:H6) is much larger than the actual copied range (i.e. B6:H6).