I feel like I am close to having my syntax set, but the compile immediately highlights certain lines red showing me they are incorrect, and I do not know how to select a designated cell in VBA. What I want to do is open a template workbook, copy an image form that workbook. Then open all workbooks in a directory, delete an image from sheet1, paste the copied image, delete an image from sheet2 and paste the copied image, save, close, next workbook.
This is my syntax, can someone help me out on what to get this working?
Sub ReplaceImage()
Dim fList() As String, fName As String, fPath As String
Dim intFno As Integer
Dim rngPaste As Range
Dim WB As Workbook, wbOpened As Workbook
Dim strmasterFile As String
Dim shape as Excel.shape
strMasterFile = “C:\Image_Template.xlsx”
Set wbOpened = Workbooks.Open(strmasterFile)
With Sheets(1)
if shape.name = "Picture 1" Then
shape.Select
Selection.Copy
end if
End With
Set WB = ActiveWorkbook
fPath = “C:\NewFormat\” & “\”
If MsgBox(“Collect all sample files in the current dir:” & vbCrLf & fPath, vbYesNo) = vbYes Then
intFno = 0
fName = Dir(fPath & “ * .xlsx”)
While fName <> “”
intFno = intFno + 1
ReDim Preserve fList(1 To intFno)
fList(intFno) = fName
fName = Dir()
Wend
If intFno = 0 Then
MsgBox “No files found”
Exit Sub
End If
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For intFno = 1 To UBound(fList)
On Error GoTo Skip
Set wbOpened = Workbooks.Open(fPath & fList(intFno))
With Sheets(1)
For Each shape In ActiveSheet.Shapes
if shape.name = "Picture 19" Then
shape.Delete
end if
next
'Paste Image to Cell A84 and of course it will expand across
End With
With Sheets(2)
For Each shape In ActiveSheet.Shapes
if shape.name = "Picture 6" Then
shape.Delete
end if
next
'Paste Image to Cell A88 and of course it will expand across
End With
wbOpened.Close False
Skip:
Next
Else: End If
End Sub
EDIT --
These are the culprit lines that immediately get font color changed to red
strMasterFile = “C:\Image_Template.xlsx”
fPath = “C:\NewFormat\” & “\”
If MsgBox(“Collect all sample files in the current dir:” & vbCrLf & fPath, vbYesNo) = vbYes Then
MsgBox “No files found”
Removing the smart quotes got rid of the immediate red-liners!!!! Now for my last piece of the pie..how to actually paste the image to the desired cell on each worksheet?
One step close-1st iteration will go issue free, 2nd workbook throws an error of
Paste method of worksheet class failed
On this line
ActiveSheet.Paste
And this is my full-updated code
Sub ReplaceImage()
Dim fList() As String, fName As String, fPath As String
Dim intFno As Integer
Dim rngPaste As Range
Dim WB As Workbook, wbOpened As Workbook
Dim strmasterFile As String
Dim shape As Excel.shape
strmasterFile = "C:\Image_Template.xlsx"
Set wbOpened = Workbooks.Open(strmasterFile)
With Sheets(1)
Rows("1:4").Select
Selection.Copy
End With
Set WB = ActiveWorkbook
fPath = "C:\NewFormat\" & "\"
If MsgBox("Collect all sample files in the current dir:" & vbCrLf & fPath, vbYesNo) = vbYes Then
intFno = 0
fName = Dir(fPath & "*.xlsx")
While fName <> “”
intFno = intFno + 1
ReDim Preserve fList(1 To intFno)
fList(intFno) = fName
fName = Dir()
Wend
If intFno = 0 Then
MsgBox "No files found"
Exit Sub
End If
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For intFno = 1 To UBound(fList)
On Error GoTo Skip
Set wbOpened = Workbooks.Open(fPath & fList(intFno))
With Sheets(1)
For Each shape In ActiveSheet.Shapes
If shape.Name = "Picture 19" Then
shape.Delete
End If
Next shape
Rows("84:84").Select
ActiveSheet.Paste
End With
With Sheets(2)
For Each shape In ActiveSheet.Shapes
If shape.Name = "Picture 6" Then
shape.Delete
End If
Next shape
Rows("88:88").Select
ActiveSheet.Paste
End With
Sheets(1).Select
wbOpened.Save
wbOpened.Close False
Skip:
Next
Else: End If
End Sub
Perhaps not the issue, but too long for a comment.
Your With blocks look funky - you're missing the leading period which ties the enclosed child items into the With object.
With Sheets(1)
Rows("1:4").Select '<< defaults to active sheet
Selection.Copy
End With
should be:
With Sheets(1)
.Rows("1:4").Select '<< leading period ties this to Sheets(1)
Selection.Copy
End With
Also:
fPath = “C:\NewFormat\” & “\”
Do you mean to terminate with two backslashes?
Related
I have 27 txt files with the same format and columns, and I want to append all of these in a single excel sheet. I have checked some previous threads here, but I could only find the code below which helped me to import txt fiels into separate sheets. However, I also want to append these separate sheets into a sheet that I want to append all my data.
Sub Test()
'UpdatebyExtendoffice6/7/2016
Dim xWb As Workbook
Dim xToBook As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xFiles As New Collection
Dim I As Long
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder [Vendor_data_25DEC]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
xFile = Dir(xStrPath)
'xFile = Dir(xStrPath & "*.txt") 'this is the original version that you can amend according to file extension
If xFile = "" Then
MsgBox "No files found", vbInformation, "Vendor_data_25DEC"
Exit Sub
End If
Do While xFile <> ""
xFiles.Add xFile, xFile
xFile = Dir()
Loop
Set xToBook = ThisWorkbook
If xFiles.Count > 0 Then
For I = 1 To xFiles.Count
Set xWb = Workbooks.Open(xStrPath & xFiles.Item(I))
xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)
On Error Resume Next
ActiveSheet.Name = xWb.Name
On Error GoTo 0
xWb.Close False
Next
End If
End Sub
I am not sure how to do this with VBA in order to combine the data in separate sheets into a single sheet quickly. I know the consolidate feature of excel but it also includes lots of manual steps, so I seek for a faster and automated solution. Any help is much appreciated.
Thanks a lot in advance.
Sub Combiner()
Dim strTextFilePath$, strFolder$
Dim wksTarget As Worksheet
Dim wksSource As Worksheet
Dim x As Long
Set wksTarget = Sheets.Add()
strFolder = "c:\Temp\test\"
strTextFilePath = Dir(strFolder)
While Len(strTextFilePath) > 0
'// "x" variable is just a counter.
'// It's purpose is to track whether the iteration is first or not.
'// If iteration is first (x=1), then we include header (zero offset down),
'// otherwise - we make an offset (1 row offset down).
x = x + 1
Set wksSource = Workbooks.Open(strFolder & strTextFilePath).Sheets(1)
With wksTarget
wksSource.Range("A1").CurrentRegion.Offset(IIf(x = 1, 0, 1)).Copy _
.Cells(.Rows.Count, 1).End(xlUp).Offset(1)
End With
wksSource.Parent.Close False
strTextFilePath = Dir()
Wend
MsgBox "Well done!", vbInformation
End Sub
I've written the following code which iterates though my worksheets of my main workbook, checks for a conditional, and then if that conditional is satisfied it copies the active worksheet into a new workbook and saves it. However, I would like to just append the worksheet to the other notebook.
Sub Archive_Sheets()
For Each ws In ActiveWorkbook.Worksheets
ws.Activate
Dim SrchRng As Range, cel As Range
Set SrchRng = ws.Range("C9:C108")
Dim bought_amt As Integer
Dim called_amt As Integer
bought_amt = 0
called_amt = 0
For Each cel In SrchRng
If InStr(1, cel.Value, "BOUGHT") > 0 Then
bought_amt = bought_amt + cel.Offset(0, 1).Value
End If
If InStr(1, cel.Value, "CALLED") > 0 Then
called_amt = called_amt + cel.Offset(0, 1).Value
End If
Next cel
If called_amt = bought_amt Then
ws.Range("A1").Value = "DONE"
Module8.CopySheet
Exit For
'ws.Delete
End If
Next
End Sub
Sub CopySheet()
Application.DisplayAlerts = False
Dim wb_name_arr() As String
pName = ActiveWorkbook.Path
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
wb_name_arr() = Split(wbName, ".")
Application.ScreenUpdating = False
ActiveSheet.Select
ActiveSheet.Copy
' NEED TO CHANGE THIS LINE ********************
ActiveSheet.SaveAs Filename:=pName + "\" + wb_name_arr(0) + " archived.xlsx"
'****************************
Application.ScreenUpdating = True
End Sub
The code above will overwrite the new workbook I'm saving to so it's only the most recent sheet. I will already have this workbook created, so if I can append active worksheets to it that would be ideal. I already tried
ActiveSheet.Copy After:=Workbook(pName + "\" + wb_name_arr(0) + " archived.xlsx")
and
ActiveSheet.Copy Before:=Workbooks.Open(pName + "\" + wb_name_arr(0) + " archived.xlsx").Sheets(0)
with no luck.
These line are pseudo-codes. The general idea is Implicit None. Try to explicitly reference to workbooks and sheets instead of activating them. Which is also faster.
Try to avoid using ActiveSheet in your code. Simply try something like this:
Set mySht = ActiveSheet 'This should be set at the beginning of your code
Then whenever you have that Sheet (i.e. ActiveSheet) in your code, use oSht instead.
So, you need to open the Workbook to be able to work on it. Similarly, you can assign a name to different workbooks like this:
Set myWbk = ActiveWorkbook
'Or
Set oWbk = Workbooks("Output.xlsx")
What #A.S.H proposed then works for you like this:
oFile = "Path/to/the/File/" & wb_name_arr(0) & " archived.xlsx"
Set oWbk = Workbooks.Open(oFile)
mySht.Copy Before:=Workbooks(oWbk).sheets(1)
Private Sub that()
Dim aRR As Variant
aRR = ThisWorkbook.Sheets("Sheet1").UsedRange
Dim colC As Long
Dim rowC As Long
colC = ThisWorkbook.Sheets("Sheet1").UsedRange.Columns.Count
rowC = ThisWorkbook.Sheets("Sheet1").UsedRange.Rows.Count
ThisWorkbook.Sheets("Sheet2").Range(ThisWorkbook.Sheets("Sheet2").Cells(1, 1), ThisWorkbook.Sheets("Sheet2").Cells(rowC, colC)).Value2 = aRR
End Sub
Try edited code (I've edited both Subs to make them shorter, and also faster as there is no need to use Select and Activate).
Explanation inside the code as comments.
Option Explicit
Sub Archive_Sheets()
Dim SrchRng As Range, cel As Range
Dim bought_amt As Long
Dim called_amt As Long
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
With ws
Set SrchRng = .Range("C9:C108")
bought_amt = 0
called_amt = 0
For Each cel In SrchRng
If cel.Value Like "BOUGHT*" Then
bought_amt = bought_amt + cel.Offset(0, 1).Value
End If
If cel.Value Like "CALLED*" Then
called_amt = called_amt + cel.Offset(0, 1).Value
End If
Next cel
If called_amt = bought_amt Then
.Range("A1").Value = "DONE"
CopySheet .Name ' <-- call the function and send the current ws sheet's name
Exit For
End If
End With
Next
End Sub
'==================================================================
Sub CopySheet(wsName As String)
Application.DisplayAlerts = False
Dim wb_name_arr() As String
Dim wb As Workbook
Dim pName As String, wbName As String
pName = ActiveWorkbook.Path
wb_name_arr() = Split(wbName, ".")
Application.ScreenUpdating = False
On Error Resume Next
Set wb = Workbooks(wb_name_arr(0) & " archived.xlsx") ' try to set wb if it's already open
On Error GoTo 0
If wb Is Nothing Then ' <-- wb is Nothing, means it's still close, open it
Set wb = Workbooks.Open(Filename:=pName & "\" & wb_name_arr(0) & " archived.xlsx")
End If
' === Copy the sheet to "archived" file one before tha last sheet ===
Worksheets(wsName).Copy before:=wb.Sheets(wb.Sheets.Count)
Application.ScreenUpdating = True
End Sub
Full code that solves problem.
Sub Archive_Sheets()
For Each ws In ActiveWorkbook.Worksheets
ws.Activate
Dim SrchRng As Range, cel As Range
Set SrchRng = ws.Range("C9:C108")
Dim bought_amt As Integer
Dim called_amt As Integer
bought_amt = 0
called_amt = 0
For Each cel In SrchRng
If InStr(1, cel.Value, "BOUGHT") > 0 Then
bought_amt = bought_amt + cel.Offset(0, 1).Value
End If
If InStr(1, cel.Value, "CALLED") > 0 Then
called_amt = called_amt + cel.Offset(0, 1).Value
End If
Next cel
If called_amt = bought_amt Then
If called_amt <> 0 Then
ws.Range("A1").Value = "DONE"
Module8.CopySheet
'ws.Delete
End If
End If
Next
End Sub
Sub CopySheet()
Application.DisplayAlerts = False
Dim wb_name_arr() As String
pName = ActiveWorkbook.Path
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
wb_name_arr() = Split(wbName, ".")
Set mySht = ActiveSheet 'This should be set at the beginning of your code
Set myWbk = ActiveWorkbook
oFile = pName & wb_name_arr(0) & " archived.xlsx"
Set oWbk = Workbooks.Open("path_to_file")
mySht.Copy after:=oWbk.Sheets(oWbk.Sheets.Count)
oWbk.Save
End Sub
Try something like this (to make it simple for the moment, I insert the sheet at beginning):
ActiveSheet.Copy Before:=Workbooks(wb_name_arr(0) & " archived.xlsx").sheets(1)
This works if the destination WB was already open. You may want to open the WB if it is not open yet. Use the following sub to create or open the destination WB:
Sub archiveSheet(ws as Worksheet)
Dim destName As String
destName = left(ThisWorkbook.name, InStrRev(ThisWorkbook.name, ".") - 1) & " archived.xlsx"
Application.DisplayAlerts = False: Application.ScreenUpdating = False
On Error Resume Next
Dim destWB As Workbook: Set destWB = Workbooks(destName)
If destWB Is Nothing Then Set destWB = Workbooks.Open(ThisWorkbook.path + "\" & destName)
If destWB Is Nothing Then
Set destWB = Workbooks.Add
destWB.SaveAs ThisWorkbook.path & "\" & destName
End If
If destWB Is Nothing Then
msgBox "could not open or create " & destName
Else
ws.Copy After:=destWB.Sheets(destWB.Sheets.count)
End If
Application.DisplayAlerts = True: Application.ScreenUpdating = True
End Sub
Call it from the main routine Archive_Sheets like this:
archiveSheet ws
After much struggle with syntax, I have following code working, but I want to use error checking to determine if file is already open using a string.
(Disclosure: I have copied comparesheets from source that I will link when I find it)
Trying to replace this code
Set wbkA = Workbooks.Open(FileName:=wba)
with
Set wBook = Workbooks(wba) 'run time error subscript out of range
If wBook Is Nothing Then
Set wbkA = Workbooks.Open(FileName:=wba)
End If
But I have syntax problem with the string wba. What is proper way use string here?
Sub RunCompare_WS2()
Dim i As Integer
Dim wba, wbb As String
Dim FileName As Variant
Dim wkbA As Workbook
Dim wkbB As Workbook
Dim wBook As Workbook
wba = "C:\c.xlsm"
wbb = "C:\d.xlsm"
'Set wBook = Workbooks(FileName:=wba) 'compiler error named argument not found
'Set wBook = Workbooks(wba) 'run time error subscript out of range
'If wBook Is Nothing Then
'Set wbkA = Workbooks.Open(FileName:=wba)
'End If
Set wbkA = Workbooks.Open(FileName:=wba)
Set wbkB = Workbooks.Open(FileName:=wbb)
For i = 1 To Application.Sheets.Count
Call compareSheets(wbkA.Sheets(i), wbkB.Sheets(i))
Next i
wbkA.Close SaveChanges:=True
wbkB.Close SaveChanges:=False
MsgBox "Completed...", vbInformation
End Sub
Sub compareSheets(shtSheet1 As Worksheet, shtSheet2 As Worksheet)
Dim mycell As Range
Dim mydiffs As Integer
Dim DifFound As Boolean
DifFound = False
sDestFile = "C:\comp-wb.txt"
DestFileNum = FreeFile()
Open sDestFile For Append As DestFileNum
'For each cell in sheet2 that is not the same in Sheet1, color it lightgreen in first file
For Each mycell In shtSheet1.UsedRange
If Not mycell.Value = shtSheet2.Cells(mycell.Row, mycell.Column).Value Then
If DifFound = False Then
Print #DestFileNum, "Row,Col" & vbTab & vbTab & "A Value" & vbTab & vbTab & "B Value"
DifFound = True
End If
mycell.Interior.Color = 5296274 'LightGreen
Print #DestFileNum, mycell.Row & "," & mycell.Column, mycell.Value, shtSheet2.Cells(mycell.Row, mycell.Column).Value '& vbInformation
mydiffs = mydiffs + 1
End If
Next
Print #DestFileNum, mydiffs & " differences found in " & shtSheet1.Name
Close #DestFileNum
End Sub
You can use On Error Resume Next to ignore any error:
Const d As String = "C:\"
wba = "c.xlsm"
On Error Resume Next
Set wBook = Workbooks(wba)
On Error Goto 0
If wBook Is Nothing Then
Set wbkA = Workbooks.Open(d & wba) 'join string d & wba
End If
This will check to see if you have the file open.
Option Explicit
Function InputOpenChecker(InputFilePath) As Boolean
Dim WB As Workbook
Dim StrFileName As String
Dim GetFileName As String
Dim IsFileOpen As Boolean
InputOpenChecker = False
'Set Full path and name of file to check if already opened.
GetFileName = Dir(InputFilePath)
StrFileName = InputFilePath & GetFileName
IsFileOpen = False
For Each WB In Application.Workbooks
If WB.Name = GetFileName Then
IsFileOpen = True
Exit For
End If
Next WB
If you dont have it open, check to see if someone else does.
On Error Resume Next
' If the file is already opened by another process,
' and the specified type of access is not allowed,
' the Open operation fails and an error occurs.
Open StrFileName For Binary Access Read Write Lock Read Write As #1
Close #1
' If an error occurs, the document is currently open.
If Err.Number <> 0 Then
'Set the FileLocked Boolean value to true
FileLocked = True
Err.Clear
End If
And one reason for your error could be the inclusion of "FileName:=" in the Workbooks.Open. Try;
Set wbkA = Workbooks.Open(wba)
Set wbkB = Workbooks.Open(wbb)
Fixed my code and reposting with corrections for clarity.
Note I moved to C:\temp since writing to root C:\ folder should not be used because many work computers have root folder locked for security as my colleague just found out!
Sub RunCompare_WS9() 'compare two WKbooks, all sheets write diff to text file
Dim i As Integer
Dim wba, wbb As String
Dim FileName As Variant
Dim wkbA As Workbook
Dim wkbB As Workbook
Dim wbook1 As Workbook
Dim wbook2 As Workbook
wba = "C:\test\c.xlsm"
wbb = "C:\test\d.xlsm"
On Error Resume Next
Set wbook1 = Workbooks(wba)
On Error GoTo 0
If wbook1 Is Nothing Then
Set wbkA = Workbooks.Open(wba)
End If
On Error Resume Next
Set wbook2 = Workbooks(wbb)
On Error GoTo 0
If wbook2 Is Nothing Then
Set wbkB = Workbooks.Open(wbb)
End If
For i = 1 To Application.Sheets.Count
Call compareSheets(wbkA.Sheets(i), wbkB.Sheets(i))
Next i
wbkA.Close SaveChanges:=True
wbkB.Close SaveChanges:=False
MsgBox "Completed...", vbInformation
End Sub
Sub compareSheets(shtSheet1 As Worksheet, shtSheet2 As Worksheet)
Dim mycell As Range
Dim mydiffs As Integer
Dim DifFound As Boolean
DifFound = False
sDestFile = "C:\Test\comp2-wb.txt"
DestFileNum = FreeFile()
Open sDestFile For Append As DestFileNum
'For each cell in sheet2 that is not the same in Sheet1, color it lightgreen in first file
For Each mycell In shtSheet1.UsedRange
If Not mycell.Value = shtSheet2.Cells(mycell.Row, mycell.Column).Value Then
If DifFound = False Then
Print #DestFileNum, "Row,Col" & vbTab & vbTab & "A Value" & vbTab & vbTab & "B Value"
DifFound = True
End If
mycell.Interior.Color = 5296274 'LightGreen
Print #DestFileNum, mycell.Row & "," & mycell.Column, mycell.Value, shtSheet2.Cells(mycell.Row, mycell.Column).Value '& vbInformation
mydiffs = mydiffs + 1
End If
Next
Print #DestFileNum, mydiffs & " differences found in " & shtSheet1.Name
Close #DestFileNum
End Sub
I am trying to create a VBA script for changing fonts in multiple workbooks kept in one folder. However, it is not working. Please take a look at the code
Sub changefont()
Dim wb As Workbook, sh As Worksheet, fpath As String, fname As String
fpath = "D:\reports"
If Right(fpath, 1) <> "\" Then fpath = fpath & "\"
fname = Dir(fpath & ".xls")
Do
On Error Resume Next
Set wb = Workbooks.Open(fname)
Set sh = wb.Sheets("REPORT")
On Error GoTo 0
If Not sh Is Nothing Then
With sh.Range(Cells(10, 1), Cells(90, 11))
.Font.Size = "18"
.Font = "Arial"
End With
End If
wb.Close True
fname = Dir
Loop While fname <> ""
End Sub
NB : my Sheet1 is named as REPORT in all the workbooks
Try this (Untested). I have added the comments at the relevant section. Do let me know if you get an error or if you have any questions.
Sub changefont()
Dim wb As Workbook, sh As Worksheet
Dim fpath As String, fname As String
fpath = "D:\reports"
If Right(fpath, 1) <> "\" Then fpath = fpath & "\"
fname = Dir(fpath & ".xls")
Do While fname <> ""
Set wb = Workbooks.Open(fname)
'~~> This is important
Set sh = Nothing
On Error Resume Next
Set sh = wb.Sheets("REPORT")
On Error GoTo 0
If Not sh Is Nothing Then
'~~> You need to fully qualify the cells object
With sh.Range(sh.Cells(10, 1), sh.Cells(90, 11))
'~> Font Size is not a string
.Font.Size = 18
'~~> Add .Name
.Font.Name = "Arial"
End With
wb.Close True
DoEvents
Else
wb.Close False
End If
fname = Dir
Loop
End Sub
As you can see in the code below, I matching worksheet names in different workbooks. Once the macro finds matching worksheet names it then is performing a SUMIF formula. The named range inside of the SUMIF formula is unique to each sheet but is consistent. (i.e. - Name of sheet is "Sheet1"...named range 1 is "Sheet1_WEEKENDING" and named range 2 is "Sheet1_FORECAST"); this is consistent through all sheets.
I want the SUMIF formula to have the worksheet variable in the named range. Example ws = sheet1
(Named range 1 = "ws_WEEKENDING" and named range 2 = "ws_FORECAST")
Code so far:
Public Sub Baseline()
Dim ws, sh As Worksheet
Dim wbMaster, wbVariance As Workbook
Dim fileOpen As Workbook
Dim folderPath As String
Const VPPName As String = "Master_Vpp.xlsm"
Const VarName As String = "Program Variance Report_Test.xlsm"
'*******************************************************************
'MUST place Master_VPP and Variance Report files in the same folder
Application.ScreenUpdating = False
folderPath = Application.ActiveWorkbook.Path & Application.PathSeparator 'assigning path to get to both workbooks folder
On Error Resume Next
fileOpen = Workbooks("Master_VPP.xlsm")
If fileOpen Is Nothing Then 'is not open
Set wbMaster = Application.Workbooks.Open(folderPath & VPPName)
End If
Set wbVariance = ActiveWorkbook 'setting variable quarter variance report
For Each ws In wbVariance.Sheets
Application.ScreenUpdating = False
ws.Activate
If (ws.Name <> "SUMMARY") And (ws.Name <> "Template") Then
For Each sh In wbMaster.Sheets
sh.Activate
If ws.Name = sh.Name Then
ws.Range("C20").Activate
ActiveCell.FormulaR1C1 = _
"=SUMIF(Master_VPP.xlsm!HNB_WEEKENDING,RC2,Master_VPP.xlsm!HNB_FORECAST)"
'"=SUMIF('[" & wbMaster & "]'!" & sh.Name & "_WEEKENDING,RC2,'[" & wbMaster & "]'!" & sh.Name & "_FORECAST)"
Selection.AutoFill Destination:=Range("C20:C33")
'Range("C20").Select
'ActiveCell.FormulaR1C1 = _
"=SUMIF('[" & wbMaster & "]'!" & ws.Name & "_WEEKENDING',RC2,'[" & wbMaster & "]'!" & ws.Name & "_FORECAST)"
'Selection.AutoFill Destination:=Range("C20:C33")
Else
GoTo Cont:
End If
Next sh
Else
GoTo Cont
Cont:
End If
Next ws
End Sub
Reviewing your code, it appears it never worked - I had assumed that it was only the formula that required adjusting. Perhaps this will do it:
Public Sub Baseline()
Dim ws As Worksheet, sh As Worksheet
Dim wbMaster As Workbook, wbVariance As Workbook
Dim fileOpen As Workbook
Dim folderPath As String
Const VPPName As String = "Master_Vpp.xlsm"
Const VarName As String = "Program Variance Report_Test.xlsm"
'*******************************************************************
'MUST place Master_VPP and Variance Report files in the same folder
Application.ScreenUpdating = False
folderPath = Application.ActiveWorkbook.Path & Application.PathSeparator 'assigning path to get to both workbooks folder
Application.ScreenUpdating = False
Set wbVariance = ActiveWorkbook 'setting variable quarter variance report
On Error Resume Next
Set fileOpen = Workbooks(VPPName)
On Error GoTo 0
If fileOpen Is Nothing Then 'is not open
Set fileOpen = Application.Workbooks.Open(folderPath & VPPName)
End If
For Each ws In wbVariance.Sheets
If (ws.Name <> "SUMMARY") And (ws.Name <> "Template") Then
On Error Resume Next
Set sh = fileOpen.Sheets(ws.Name)
On Error GoTo 0
If Not sh Is Nothing Then
With ws.Range("C20")
.FormulaR1C1 = _
"=SUMIF(" & VPPName & "!" & sh.Name & "_WEEKENDING,RC2," & VPPName & "!" & sh.Name & "_FORECAST)"
.AutoFill Destination:=ws.Range("C20:C33")
End With
Set sh = Nothing
End If
End If
Next ws
End Sub