I am trying to set up a VBA macro to update link paths in excel. I looked up some code online and tried to put it together, and am getting errors. I am wondering if i could get some direction here. Please note that i am not a programmer by profession, just trying to reduce some manual updating work.
Cheers!
Private Sub CommandButton1_Click()
Dim FolderPath As String
Dim FSO As Object
Dim bookname As String
Dim wbook As Workbook
Dim oldname As String
Dim newname As String
oldname = "C:\Users\XX\Documents\[Broadstreet.xlsx]"
newname = "C:\Users\XX\Documents\[Broadstreet2.xlsx]"
FolderPath = "C:\Users\XX\Documents1"
With Application
.ScreenUpdating = False
.AskToUpdateLinks = False
End With
For Each Workbook In FSO.GetFolder(FolderPath).Files
bookname = Workbook.Name
MsgBox (bookname)
Set wb = Workbooks.Open(FolderPath & "\" & bookname)
ActiveWorkbook.ChangeLink oldname1, newname1, xlLinkTypeExcelLinks
wb.Close SaveChanges:=True
Next
Application.ScreenUpdating = True
End Sub
Workbooks in Folder Treatment
Loops through all Excel files (workbooks) in a folder, opens each one, changes a link from one document to another, saves the changes and closes the workbook.
xlLinkTypeExcelLinks is the default parameter of the Type
argument of the ChangeLink method and can therefore be omitted.
.Close True can be used in this way because SaveChanges is the
first argument of the Close method.
The Code
Private Sub CommandButton1_Click()
Const strOld As String = "C:\Users\XX\Documents\[Broadstreet.xlsx]"
Const strNew As String = "C:\Users\XX\Documents\[Broadstreet2.xlsx]"
Const strPath As String = "C:\Users\XX\Documents1"
Const strExt As String = "*.xls*"
Dim strName As String
With Application
.ScreenUpdating = False
.AskToUpdateLinks = False
End With
On Error GoTo ProcedureExit
strName = Dir(strPath & "\" & strExt)
Do While strName <> ""
With Workbooks.Open(strPath & "\" & strName)
.ChangeLink strOld, strNew
.Close True
End With
strName = Dir
Loop
ProcedureExit:
With Application
.AskToUpdateLinks = True
.ScreenUpdating = True
End With
End Sub
Related
I have a macro that I partly created and pieced together from other codes. The intent of the the macro is to search all Excel files in my desktop folder called Financials -- it has approximately 25 files -- and to copy and paste into a new document all Worksheets that have the word (State) anywhere in the name; combine those Worksheets into 1 document and save the it my desktop folder called Final.
The code only saves a blank document to my folder and doesn't execute the other code
I have tried rearranging the code sequence
Sub CombineState()
Dim wbOpen As Workbook
Dim wbNew As Workbook
Const strPath As String = "C:\Users\johnson\Desktop\Financials"
Dim strExtension As String
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
On Error Resume Next
ChDir strPath
strExtension = Dir("*.xlsx")
Set wbNew = Workbooks.Add
wbNew.SaveAs Filename:="C:\Users\johnson\Desktop\Final\Financial Metrics for State", FileFormat:=xlWorkbookNormal
Do While strExtension <> ""
Set wbOpen = Workbooks.Open(strPath & strExtension)
Dim checkSheet As Worksheet
For Each checkSheet In wbOpen.Worksheets
If UCase$(checkSheet.Name) Like "*State*" Then
checkSheet.Copy After:=wbNew.Sheets(wbNew.Sheets.Count)
wbNew.Sheets(wbNew.Sheets.Count).Name = wbNew.Sheets(wbNew.Sheets.Count).Cells(1, 1)
End If
Next
wbOpen.Close SaveChanges:=False
strExtension = Dir
Loop
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
On Error GoTo 0
End Sub
Hypothetically speaking, if 3 documents contain State anywhere in the worksheet name, the new document will have 3 worksheets and be saved to my Final folder.
You were close. See the comment:
Sub CombineState()
Dim wbOpen As Workbook
Dim wbNew As Workbook
Const strPath As String = "C:\Users\johnson\Desktop\Financials\" ' Add the backslash at the end
Dim strExtension As String
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
On Error Resume Next
ChDir strPath
strExtension = Dir("*.xlsx")
Set wbNew = Workbooks.Add
wbNew.SaveAs Filename:="C:\Users\johnson\Desktop\Final\Financial Metrics for State", FileFormat:=xlWorkbookNormal
Do While strExtension <> ""
Set wbOpen = Workbooks.Open(strPath & strExtension)
Dim checkSheet As Worksheet
For Each checkSheet In wbOpen.Worksheets
If UCase$(checkSheet.Name) Like "*STATE*" Then
checkSheet.Copy After:=wbNew.Sheets(wbNew.Sheets.Count)
wbNew.Sheets(wbNew.Sheets.Count).Name = wbNew.Sheets(wbNew.Sheets.Count).Cells(1, 1)
End If
Next
wbOpen.Close SaveChanges:=False
strExtension = Dir
Loop
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
On Error GoTo 0
End Sub
I am trying to copy specific collections sheets within an excel workbook in separate workbooks. Not being a vba coder I have used and adapted code found here and other resource sites. I believe I am now very close having grasped the basic concepts but cannot figure out what i am doing wrong, triggering the below code causes the first new workbook to be created and the first sheet inserted but breaks at that point.
My code is below, additional relevant info - there is a sheet called 'List' which has a column of names. Each name on the list has 2 sheets which I am trying to copy 2 by 2 into new sheet of the same name. the sheets are labelled as the name and the name + H (e.g Bobdata & BobdataH)
Sub SheetCreate()
'
'Creates an individual workbook for each worksname in the list of names.
'
Dim wbDest As Workbook
Dim wbSource As Workbook
Dim sht As Object
Dim strSavePath As String
Dim sname As String
Dim relativePath As String
Dim ListOfNames As Range, LRow As Long, Cell As Range
With ThisWorkbook
Set ListSh = .Sheets("List")
End With
LRow = ListSh.Cells(Rows.Count, "A").End(xlUp).Row '--Get last row of list.
Set ListOfNames = ListSh.Range("A1:A" & LRow) '--Qualify list.
With Application
.ScreenUpdating = False '--Turn off flicker.
.Calculation = xlCalculationManual '--Turn off calculations.
End With
Set wbSource = ActiveWorkbook
For Each Cell In ListOfNames
sname = Cell.Value & ".xls"
relativePath = wbSource.Path & "\" & sname
Sheets(Cell.Value).Copy
Set wbDest = ActiveWorkbook
Application.DisplayAlerts = False
ActiveWorkbook.CheckCompatibility = False
ActiveWorkbook.SaveAs Filename:=relativePath, FileFormat:=xlExcel8
Application.DisplayAlerts = True
wbSource.Activate
Sheets(Cell.Value & "H").Copy after:=Workbooks(relativePath).Sheets(Cell.Value)
wbDest.Save
wbDest.Close False
Next Cell
MsgBox "Done!"
End Sub
You can try to change
Sheets(Cell.Value & "H").Copy after:=Workbooks(relativePath).Sheets(Cell.Value)
to
Sheets(Cell.Value & "H").Copy after:=wbDest.Sheets(Cell.Value)
Also it would be good idea to check if file already exists in selected location. For this you can use function:
Private Function findFile(ByVal sFindPath As String, Optional sFileType = ".xlsx") As Boolean
Dim obj_fso As Object: Set obj_fso = CreateObject("Scripting.FileSystemObject")
findFile = False
findFile = obj_fso.FileExists(sFindPath & "/" & sFileType)
Set obj_fso = Nothing
End Function
and change sFileType = ".xlsx" to "*" or other excet file type.
This was the code i created to create a new workbook and then copy sheet contents from existing one to the new one. Hope it helps.
Private Sub CommandButton3_Click()
On Error Resume Next
Application.ScreenUpdating = False
Application.DisplayAlerts = False
TryAgain:
Flname = InputBox("Enter File Name :", "Creating New File...")
MsgBox Len(Flname)
If Flname <> "" Then
Set NewWkbk = Workbooks.Add
ThisWorkbook.Sheets(1).Range("A1:J100").Copy
NewWkbk.Sheets(1).Range("A1:J100").PasteSpecial
Range("A1:J100").Select
Selection.Columns.AutoFit
AddData
Dim FirstRow As Long
Sheets("Sheet1").Range("A1").Value = "Data Recorded At-" & Format(Now(), "dd-mmmm-yy-h:mm:ss")
NewWkbk.SaveAs ThisWorkbook.Path & "\" & Flname
If Err.Number = 1004 Then
NewWkbk.Close
MsgBox "File Name Not Valid" & vbCrLf & vbCrLf & "Try Again."
GoTo TryAgain
End If
MsgBox "Export Complete Close the Application."
NewWkbk.Close
End If
End Sub
When I try to save my file with the ActiveWorkbook.Save function. The file get's corrupted and i cannot use it anymore.
I already tried the ActiveWorkbook.SaveCopyAs function, but the result is the same. Below the example. I have added the 2 other functions used on the bottom.
Sub Publish_WB()
Dim ws As Worksheet
Dim cell As Range
Dim CurrentPath, OriginalFname, NewFname, FName As String
If CheckPublished() Then
MsgBox ("Published version, feature not available ...")
Exit Sub
End If
NoUpdate
PublishInProgress = True
'Save the Current Workbook
OriginalFname = ActiveWorkbook.Path & "\" & ThisWorkbook.Name
'Store the current path
CurrentPath = CurDir
'Change the path to the same of the current sheet
SetCurrentDirectory ActiveWorkbook.Path
NewFname = Replace(ThisWorkbook.Name, ".xlsm", "_published.xlsm")
FName = Application.GetSaveAsFilename(FileFilter:="Excel files (*.xlsm),*.xlsm", InitialFileName:=NewFname, Title:="Save Published Version as")
If FName <> "" Then
ActiveWorkbook.SaveAs FName, 52
ActiveWorkbook.SaveCopyAs (OriginalFname)
Else
'user has cancelled
GoTo einde
End If
function CheckPublished()
Function CheckPublished() As Boolean
If Range("Quoting_Tool_Published").Value = True Then
CheckPublished = True
Else
CheckPublished = False
End If
End Function
and the NoUpdate :
Sub NoUpdate()
If NoUpdateNested = 0 Then
CurrentCalculationMode = Application.Calculation 'store previous mode
End If
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
'Application.Cursor = xlWait
NoUpdateNested = NoUpdateNested + 1
' Debug.Print "NoUpdate, Noupdatenested = " & NoUpdateNested
End Sub
if we jump to einde, I call the following function :
Sub UpdateAgain()
NoUpdateNested = NoUpdateNested - 1
If NoUpdateNested < 1 Then
Application.Calculation = xlCalculationAutomatic 'let all sheets be calculated again first
Application.Calculation = CurrentCalculationMode 'set to previous mode
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Cursor = xlDefault
Else
Application.Calculation = xlCalculationAutomatic 'recalculate sheets, but keep the rest from updating
Application.Calculation = xlCalculationManual
End If
'Debug.Print "UpdateAgain, Noupdatenested = " & NoUpdateNested
End Sub
By using a name for the workbook than rather activeworkbook I was able to solve the problem; the rest of the code is the same, so the rest was not causing any issues.
Sub Publish_WB()
Dim ws As Worksheet
Dim wb as Workbook
Dim cell As Range
Dim CurrentPath, OriginalFname, NewFname, FName As String
If CheckPublished() Then
MsgBox ("Published version, feature not available ...")
Exit Sub
End If
NoUpdate
PublishInProgress = True
'Save the Current Workbook
Set wb = ThisWorkbook
wb.Save
'Store the current path
CurrentPath = CurDir
'Change the path to the same of the current sheet
SetCurrentDirectory ActiveWorkbook.Path
NewFname = Replace(ThisWorkbook.Name, ".xlsm", "_published.xlsm")
FName = Application.GetSaveAsFilename(FileFilter:="Excel files (*.xlsm),*.xlsm", InitialFileName:=NewFname, Title:="Save Published Version as")
If FName <> "" Then
wb.SaveAs FName, 52
Else
'user has cancelled
GoTo einde
End If
I'm trying to write code that on Commandbutton2_Click searches through the folder that the file is in, takes a value from the same cell in each file and adds these together.
I have this:
Private Sub CommandButton2_Click()
Dim lCount As Long
Dim wbResults As Workbook
Dim wbCodeBook As Workbook
Dim strFolderPath As String
Dim strToolNumber As String
Dim RingCount As Integer
RingCount = 0
strToolNumber = CStr(Sheets("Sheet1").Range("B9").Value)
strFolderPath = "T:\Engineering\Tooling\Tooling Control Engineering\Press Tool Inspection Records\" & strToolNumber & "\"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
On Error Resume Next
Set wbCodeBook = ThisWorkbook
With Application.FileSearch
.NewSearch
'Change path to suit
.LookIn = strFolderPath
.FileType = msoFileTypeExcelWorkbooks
If .Execute > 0 Then 'Workbooks in folder
For lCount = 1 To .FoundFiles.Count 'Loop through all
'Open Workbook x and Set a Workbook variable to it
Set wbResults = Workbooks.Open(FileName:=.FoundFiles(lCount), UpdateLinks:=0)
'DO YOUR CODE HERE
RingCount = Val(RingCount) + ActiveWorkbook.Sheets("Sheet1").Range("F11").Value
wbResults.Close SaveChanges:=False
Next lCount
End If
End With
On Error GoTo 0
ActiveSheet.Unprotect Password:=""
ActiveWorkbook.Sheets("Sheet1").Range("F13").Value = (RingCount + ActiveWorkbook.Sheets("Sheet1").Range("F11").Value)
ActiveSheet.Protect Password:=""
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub
whose main body was pieced together from different google searches - but it continually returns a value of 0 (despite the cells in the other sheets having values).
I read somewhere that Application.Filesearch does not work for versions of Excel later than 2003, could this be the source of the problem?
Its possible to pull that value youre interested in without opening each workbook. Its much more efficient and reliable.
This code iterates through all files in the path variable and pulls values without opening the Excel files. It then prints the values starting at F20. You can then make another wrapper function to sum them up and delete or whatever you want. Hope this helps
Private Sub CommandButton2_Click()
Dim tool As String
tool = CStr(Sheets("Sheet1").range("B9").Value)
Dim path As String
path = "T:\Engineering\Tooling\Tooling Control Engineering\Press Tool Inspection Records\" & strToolNumber & "\"
Dim fname
fname = Dir(CStr(path)) ' gets the filename of each file in each folder
Do While fname <> ""
If fname <> ThisWorkbook.Name Then
PullValue path, fname ' add values
End If
fname = Dir ' get next filename
Loop
End Sub
Private Sub PullValue(path As String, ByVal fname As String)
With range("F" & (range("F" & Rows.Count).End(xlUp).Row + 1))
.Formula = "='" & path & "[" & fname & "]Sheet1'!F11"
.Value = .Value
End With
End Sub
Hi I'm facing a problem on dealing with converting Excel spreadsheets to txt files.
What I want to do is to create a Macro which can takes all the xls files in one folder and convert them to txt files.
The code currently working on
Sub Combined()
Application.DisplayAlerts = False
Const fPath As String = "C:\Users\A9993846\Desktop\"
Dim sh As Worksheet
Dim sName As String
Dim inputString As String
With Application
.Calculation = xlCalculationManual
.EnableEvents = False
.ScreenUpdating = False
End With
sName = Dir(fPath & "*.xls*")
Do Until sName = ""
With GetObject(fPath & sName)
For Each sh In .Worksheets
With sh
.SaveAs Replace(sName, ".xls*", ".txt"), 42 'UPDATE:
End With
Next sh
.Close True
End With
sName = Dir
Loop
With Application
.Calculation = xlAutomatic
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
But It's not working as expected, I have 0 knowledge on VB. Anyone willing to give a hand?
The code below converts all Excel Workbooks (tests file extension for "xlsx") in a given folder into CSV files. File names will be [workbookname][sheetname].csv, ie "foo.xlsx" will get "foo.xlsxSheet1.scv", "foo.xlsxSheet2.scv", etc. In order to run it, create a plain text file, rename it to .vbs and copy-paste the code below. Change path info and run it.
Option Explicit
Dim oFSO, myFolder
Dim xlCSV
myFolder="C:\your\path\to\excelfiles\"
Set oFSO = CreateObject("Scripting.FileSystemObject")
xlCSV = 6 'Excel CSV format enum
Call ConvertAllExcelFiles(myFolder)
Set oFSO = Nothing
Call MsgBox ("Done!")
Sub ConvertAllExcelFiles(ByVal oFolder)
Dim targetF, oFileList, oFile
Dim oExcel, oWB, oWSH
Set oExcel = CreateObject("Excel.Application")
oExcel.DisplayAlerts = False
Set targetF = oFSO.GetFolder(oFolder)
Set oFileList = targetF.Files
For Each oFile in oFileList
If (Right(oFile.Name, 4) = "xlsx") Then
Set oWB = oExcel.Workbooks.Open(oFile.Path)
For Each oWSH in oWB.Sheets
Call oWSH.SaveAs (oFile.Path & oWSH.Name & ".csv", xlCSV)
Next
Set oWSH = Nothing
Call oWB.Close
Set oWB = Nothing
End If
Next
Call oExcel.Quit
Set oExcel = Nothing
End Sub
You can give better file naming, error handling/etc if needed.
The issue with your code is that you define sPath as a path containing wildcard characters:
sName = Dir(fPath & "*.xls*")
and replace only the extension portion (.xls*), but leave the wildcard character before the extension in place:
Replace(sName, ".xls*", ".txt")
This produces the following path:
C:\Users\A9993846\Desktop\*.txt
which causes the error you observed, because the SaveAs method tries to save the spreadsheet to a file with the literal name *.txt, but * is not a valid character for file names.
Replace this:
.SaveAs Replace(sName, ".xls*", ".txt"), 42
with this:
Set wb = sh.Parent
basename = Replace(wb.FullName, Mid(wb.Name, InStrRev(wb.Name, ".")), "")
.SaveAs basename & "_" & sh.Name & ".txt", xlUnicodeText