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
Related
I'm trying to use msoFileDialogFolderPicker to select a folder and then loop through the folder. I can't seem to get Do While Len(myFile) > 0 to trigger with FolderPicker if I specifyfilepath with C:\Test\ it works perfectly.
Option Explicit
Sub LoopThroughDirectory()
Dim myFile As String, filepath As String
Dim wbc As Long, ws As Worksheet, wb As Workbook
Dim diaFolder As FileDialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
If diaFolder.Show = -1 Then
myFile = diaFolder.SelectedItems(1)
End If
wbc = 0
filepath = diaFolder
Application.ScreenUpdating = False
'Only try to open xlsm workbooks
myFile = Dir(filepath & "*.xlsm*")
Do While Len(myFile) > 0
'Make sure myFile isn't ThisWorkbook
If Split(myFile & ".", ".")(0) <> Split(ThisWorkbook.Name & ".", ".")(0) Then
Set wb = Workbooks.Open(Filename:=filepath & myFile, ReadOnly:=True)
'Check if there is a Results worksheet
On Error Resume Next
Set ws = wb.Worksheets("Results")
On Error GoTo 0
If Not ws Is Nothing Then
'Transfer cells B2 & C2 from the results worksheet
With ws.Range("A2:B2")
ThisWorkbook.Worksheets("AMT").Range("B4").Offset(wbc, 0).Resize(.Rows.Count, .Columns.Count) = .Value
End With
End If
'Close wb most recently opened
wb.Close SaveChanges:=False
wbc = wbc + 1
If wbc > 1000 Then Exit Do
End If
Set ws = Nothing
myFile = Dir
Loop
ActiveWorkbook.Save
End Sub
The reason it does not work is because you assign myFile to the wrong variable:
Your code:
filepath = diaFolder
Correct code:
filepath = myFile
PLUS
myFile = Dir(filepath & "*.xlsm*")
should be
myFile = Dir(filepath & "\*.xlsm")
This macro loops through all the files in a directory and formats the data as a table.
I need to sort Column J on the table from Largest to Smallest and then save the file before moving onto the next file. Currently it leaves all the files open.
Sub LoopThroughFiles()
FolderName = "C:\Folder1\"
If Right(FolderName, 1) <> Application.PathSeparator Then FolderName = FolderName & Application.PathSeparator
Fname = Dir(FolderName & "*.xls")
'loop through the files
Do While Len(Fname)
With Workbooks.Open(FolderName & Fname)
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium2"
Columns("A:L").Select
Columns("A:L").EntireColumn.AutoFit
End With
'go to the next file in the folder
Fname = Dir
Loop
End Sub
You are missing the line where you Close the workbook : WB.Close True.
(if you don't want to save the changes made to the workbook use WB.Close False)
Note: you are not setting the Worksheet object on the workbook you open, so by default it will assume the ActiveSheet, which is the last ActiveSheet the last time you saved this workbook.
Try the code below:
Sub LoopThroughFiles()
Dim WB As Workbook
FolderName = "C:\Folder1\"
If Right(FolderName, 1) <> Application.PathSeparator Then FolderName = FolderName & Application.PathSeparator
fname = Dir(FolderName & "*.xls")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'loop through the files
Do While Len(fname)
Set WB = Workbooks.Open(FolderName & fname) '<-- set the workbook object
With WB
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium2"
Columns("A:L").Select
Columns("A:L").EntireColumn.AutoFit
End With
WB.Close True ' <-- close workbook and save changes
' go to the next file in the folder
fname = Dir
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
As the title says, I'm trying to push contents of a range of cells from a source workbook to the same range in a target (closed) workbook. I'm using the following code:
Option Explicit
Sub UpdateAdminBook()
Dim MyPath As String
Dim MyFile As String
Dim Wkb As Workbook
Dim Cnt As Long
Application.ScreenUpdating = False
MyPath = "C:FILEPATH\" 'change the path accordingly
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "Administration.xlsx")
Cnt = 0
Do While Len(MyFile) > 0
Cnt = Cnt + 1
Set Wkb = Workbooks.Open(MyPath & MyFile)
Wkb.Worksheets("Administration").Range("D18:D37").Value = ActiveWorkbook.Sheets("Administration").Range("D18:D37") 'change the new value accordingly
Wkb.Close savechanges:=True
MyFile = Dir
Loop
If Cnt > 0 Then
MsgBox "Completed...", vbExclamation
Else
MsgBox "No files were found!", vbExclamation
End If
Application.ScreenUpdating = True
End Sub
I'm having trouble starting at "ActiveWorkbook" and I keep getting "TRUE" or blanks. Any idea how I can fix this?
When you open a workbook, it becomes the active workbook, rather than the original workbook. Change to this
Dim wbSrc As Workbook
Set wbSrc = ActiveWorkbook
'...
Do ...
' ...
Set Wkb = Workbooks.Open(MyPath & MyFile)
Wkb.Worksheets("Administration").Range("D18:D37").Value = wbSrc.Sheets("Administration").Range("D18:D37") 'change the new value accordingly
you could assume your copying range as reference in a With - End With block
Sub UpdateAdminBook()
Dim MyPath As String
Dim MyFile As String
Dim Cnt As Long
Application.ScreenUpdating = False
MyPath = "C:FILEPATH\" 'change the path accordingly
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "Administration.xlsx")
With ActiveWorkbook.Sheets("Administration").Range("D18:D37")
Cnt = 0
Do While Len(MyFile) > 0
Cnt = Cnt + 1
Workbooks.Open(MyPath & MyFile).Worksheets("Administration").Range("D18:D37").Value = .Value 'change the new value accordingly
ActiveWorkbook.Close savechanges:=True
MyFile = Dir
Loop
End With
If Cnt > 0 Then
MsgBox "Completed...", vbExclamation
Else
MsgBox "No files were found!", vbExclamation
End If
Application.ScreenUpdating = True
End Sub
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?
I have a source folder that contains many xls files. I want to create a master file - collect all information into one database from all files in the given source.
The following code creates 2 columns in master file and enters 2 values from the given source file (one file):
Sub getData()
Dim XL As Excel.Application
Dim WBK As Excel.Workbook
Dim scrFile As String
Dim myPath As String
myPath = ThisWorkbook.path & "\db\" 'The source folder
scrFile = myPath & "1.xlsx" 'Select first file
' Sheet name in the master file is "Sh"
ThisWorkbook.Sheets("Sh").Range("A1").Value = "Column 1"
ThisWorkbook.Sheets("Sh").Range("B1").Value = "Column 2"
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(scrFile)
ThisWorkbook.Sheets("Sh").Range("A2").Value = WBK.ActiveSheet.Range("A10").Value
ThisWorkbook.Sheets("Sh").Range("B2").Value = WBK.ActiveSheet.Range("C5").Value
WBK.Close False
Set XL = Nothing
Application.ScreenUpdating = True
End Sub
Now I want to loop through all files and save the values from cells "A10" and "C5" from each file in one database, so the loop should select the next row to save new values.
I have an idea how to loop through all files, but don't know how to switch to the next row:
scrFile = Dir(myPath & "*.xlsx")
Do While scrFile <> ""
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(scrFile)
' Here should be the code to save the values of A10 and C5 of the given file
'in the loop in next available row of the master file.
WBK.Close False
Set XL = Nothing
scrFile = Dir
Loop
Any help will be highly appreciated! :)
For simplicity, just use a counter:
scrFile = Dir(myPath & "*.xlsx")
n = 1 ' skip the first row with headers
Do While scrFile <> ""
n = n + 1
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(scrFile)
' save the values of A10 and C5 of the given file in the next row
ThisWorkbook.Sheets("Sh").Range("A" & n).Value = WBK.ActiveSheet.Range("A10").Value
ThisWorkbook.Sheets("Sh").Range("B" & n).Value = WBK.ActiveSheet.Range("C5").Value
WBK.Close False
Set XL = Nothing
scrFile = Dir
Loop
msgbox n & " files imported."
BTW, you don't need to start a second Excel instance (CreateObject("Excel.Application")) just to open a second workbook. This will slow down your code a lot. Just open, read and close it. Address your master workbook not by ThisWorkbook but assign a varible to it:
Dim masterWB As Excel.Workbook
set masterWB = ThisWorkbook
...
masterWB.Sheets("Sh").Range("A" & n).Value = WBK.ActiveSheet.Range("A10").Value
You need to recalculate last row in the loop wtih End() function.
Like this for range .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0)
Or to have an integer .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0).Row
Give this a try :
Sub getData()
Application.ScreenUpdating = False
Dim XL As Excel.Application, _
WBK As Excel.Workbook, _
MS As Worksheet, _
scrFile As String, _
myPath As String
'Sheet name in the master file is "Sh"
Set MS = ThisWorkbook.Sheets("Sh")
'The source folder
myPath = ThisWorkbook.Path & "\db\"
MS.Range("A1").Value = "Column 1"
MS.Range("B1").Value = "Column 2"
Set XL = CreateObject("Excel.Application")
scrFile = Dir(myPath & "*.xlsx")
Do While scrFile <> ""
Set WBK = XL.Workbooks.Open(scrFile)
' Here should be the code to save the values of A10 and C5 of the given file
'in the loop in next available row of the master file.
With MS
.Range("A" & .Rows.Count).End(xlUp).Offset(1, 0).Value = WBK.ActiveSheet.Range("A10").Value
.Range("B" & .Rows.Count).End(xlUp).Offset(1, 0).Value = WBK.ActiveSheet.Range("C5").Value
End With
WBK.Close False
scrFile = Dir
Loop
XL.Quit
Set XL = Nothing
Set MS = Nothing
Set WBK = Nothing
Application.ScreenUpdating = True
End Sub
I actually have a code here that will loop through each file and deposit the code into your main file. You are also able to choose the directory of the target folder.
Sub GatherData()
Dim sFolder As String
Application.ScreenUpdating = True
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder..."
.Show
If .SelectedItems.Count > 0 Then
sFolder = .SelectedItems(1) & "\"
Else
Exit Sub
End If
End With
Call Consolidate(sFolder, ThisWorkbook)
End Sub
Private Sub Consolidate(sFolder As String, wbMaster As Workbook)
Dim wbTarget As Workbook
Dim objFso As Object
Dim objFiles As Object
Dim objSubFolder As Object
Dim objSubFolders As Object
Dim objFile As Object
Dim ary(3) As Variant
Dim lRow As Long
'Set Error Handling
On Error GoTo EarlyExit
'Create objects to enumerate files and folders
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFiles = objFso.GetFolder(strFolder).Files
Set objSubFolders = objFso.GetFolder(strFolder).subFolders
'Loop through each file in the folder
For Each objFile In objFiles
If InStr(1, objFile.Path, ".xls") > 0 Then
Set wbTarget = Workbooks.Open(objFile.Path)
With wbTarget.Worksheets(1)
ary(0) = .Range("B8") 'here you can change the cells you need the data from
ary(1) = .Range("B12")
ary(2) = .Range("B14")
End With
With wbMaster.Worksheets(1)
lRow = .Range("E" & .Rows.Count).End(xlUp).Offset(1, 0).Row 'here you can change the row the data is deposited in
.Range("E" & lRow & ":G" & lRow) = ary
End With
wbTarget.Close savechanges:=False
End If
Next objFile
'Request count of files in subfolders
For Each objSubFolder In objSubFolders
Consolidate objSubFolder.Path, wbMaster
Next objSubFolder
EarlyExit:
'Clean up
On Error Resume Next
Set objFile = Nothing
Set objFiles = Nothing
Set objFso = Nothing
On Error GoTo 0
End Sub