Auto changing links between workbook in formulas - excel

I have code that auto changes formula links from another workbook.
On my laptop (Windows 10 office 365) I get a runtime error and asks me to debug the following line.
ThisWorkbook.ChangeLink Name:=strLink, NewName:=strLinkNew, Type:=xlExcelLinks
It runs on a computer running windows 7 Office 2010.
The whole code:
Dim strFile As String
Dim aLinks As Variant
Dim i As Long
Dim strLink As String
Dim strLinkNew As String
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
strLinkNew = .SelectedItems(1)
aLinks = ThisWorkbook.LinkSources(xlExcelLinks)
If Not IsEmpty(aLinks) Then
For i = 1 To UBound(aLinks)
strLink = aLinks(i)
If strLink Like "*\CRiSP*.xlsm" Then
'Change Linked File
Sheets("Links").Select
ThisWorkbook.Worksheets("Links").Unprotect "MYPASSWORD"
ThisWorkbook.ChangeLink Name:=strLink, NewName:=strLinkNew, Type:=xlExcelLinks
ThisWorkbook.Worksheets("Links").Protect "MYPASSWORD"
End If
Next
End If
End If
End With
Sheets("Main Menu").Select
Cells(1, 1).Select
Dim flToSave As Variant
Dim flName As String
Dim flFormat As Long
flFormat = ActiveWorkbook.FileFormat
flName = Range("A1") & Range("A2").Text
flToSave = Application.GetSaveAsFilename _
(ThisWorkbook.Path & "\" & flName, filefilter:="Excel Files (*.xlsm), *.xlsm", _
Title:="Save FileAs...")
If flToSave = False Then
Exit Sub
Else
ThisWorkbook.SaveAs Filename:=flToSave, FileFormat:=flFormat
End If
End Sub

I had the same error 1004 challenge but solved it by ensuring that both the 'Name' and 'NewName' files were present at their paths.

this function will update the links while at the same time fixes a strange bug i was trying to stomp on for a while, if a link is not used in the active sheet then excel gives you error 1004
'''''''''''''''''
Private Function UpdateXlsLinkSource(oldLinkPathAndFile As String, newLinkPathAndFile As String) As Boolean
UpdateXlsLinkSource = False
Dim lSources As Variant
lSources = ThisWorkbook.LinkSources(xlExcelLinks) 'array that contains all the links with path to excel files
Dim FILE_NAME As String
FILE_NAME = Right(newLinkPathAndFile, Len(newLinkPathAndFile) - InStrRev(newLinkPathAndFile, "\")) 'name of the file without path
Dim theFileIsAlreadyOpen As Boolean
theFileIsAlreadyOpen = file_open_module.IsWorkBookOpen(FILE_NAME) 'will check if the file is is open and return true or false
'check if a file with the same name is already open
If theFileIsAlreadyOpen Then
newLinkPathAndFile = Workbooks(FILE_NAME).PATH & "\" & Workbooks(FILE_NAME).Name 'use the open file
Else
Workbooks.Open FileName:=newLinkPathAndFile 'open the file if it wasn't already open
End If
theFileIsAlreadyOpen = True
'CHECK IF THE FILE NEEDS UPDATING
If newLinkPathAndFile = oldLinkPathAndFile Then
UpdateXlsLinkSource = True 'if the link is unchanged update the values
Exit Function
Else
'step thru the existing links and see if it exists
For Each Link In lSources
If Link = oldLinkPathAndFile Then
'''''''''''''''''''''''''''''''''''''
For Each SHEET In ThisWorkbook.Worksheets 'this seemingly useless loop handles a bug where if a link is not referenced in the active sheet it crashes
SHEET.Activate
On Error Resume Next
'''''''''''''''''''''''''''''''''''''
ThisWorkbook.Activate
ThisWorkbook.ChangeLink Name:=Link, NewName:=newLinkPathAndFile, Type:=xlExcelLinks 'update the link
UpdateXlsLinkSource = True
'''''''''''''''''''''''''''''''''''''
If Err = 0 Then
On Error GoTo 0
Exit For
End If
Next SHEET
'''''''''''''''''''''''''''''''''''''
Exit For
End If
Next Link
'check if the link was found AND WARN IF IT WAS NOT
If Not UpdateXlsLinkSource Then
MsgBox "Link to target not found"
Exit Function
End If
If Not theFileIsAlreadyOpen Then 'CHECK IF THE FILE IS CLOSED, IF IT IS THEN OPEN IT
Workbooks.Open (newLinkPathAndFile)
End If
End If
End Function
'''''''''''''

Related

Workbook.Activate method

i got a variable:
V_WBNameOutPut as string
and use it inside the following code:
Application.Workbooks(V_WBNameOutPut).Activate
This two part of code are inside a huger code which work fine for 99.99% of different users, but only for one user the code go in error and when I debug its stop to Application.Workbooks(V_WBNameOutPut).Activate line.
And the error is the following:
Runtime Error 9: Subscript Out of Range
Any ideas why this happend and possible solution?
Thanks
I try it to debug but the code works fine but for one particular user it doesn't
The subroutine to generate the output file, which the Application.Workbooks(V_WBNameOutPut).Activate refers to:
Sub CreateWB()
Dim File_Name As Variant
Dim File_Name_Saved As String
Dim i_attempt As Integer
Dim NewWorkBook As Workbook
Set NewWorkBook = Workbooks.Add
Do While i_attempt < 2
i_attempt = i_attempt + 1
File_Name = Application.GetSaveAsFilename(InitialFileName:=V_WBNameOutPut, filefilter:="Excel Files(*.xlsx),*.xlsx,Excel-Macro Files (*.xlsm),*.xlsm", Title:="Please choose a Folder")
File_Name_Saved = Left(Right(File_Name, Len(V_WBNameOutPut) + 5), Len(V_WBNameOutPut))
If File_Name = False Then
ActiveWorkbook.Close
End
Else
If UCase(File_Name_Saved) <> UCase(V_WBNameOutPut) Then
If i_attempt < 2 Then
MsgBox "Please do not change the File name" & vbCrLf & i_attempt & "/2 Attempt"
Else
ActiveWorkbook.Close
End
End If
Else
Application.DisplayAlerts = False
NewWorkBook.SaveAs File_Name, ConflictResolution:=True
Exit Do
End If
End If
Loop
End Sub
You can loop through the open workbooks looking for a match without the file extension. A better solution would be to make CreateWB a function that returns the saved filename.
Option Explicit
Dim V_WBNameOutPut
Sub test()
Dim wb As Workbook
V_WBNameOutPut = "test2"
CreateWB
For Each wb In Workbooks
If wb.Name Like V_WBNameOutPut & "*" Then
wb.Activate
Exit For
End If
Next
Sheets(1).Cells(1, 1).Select ' active workbook
End Sub
Sub CreateWB()
Dim NewWorkBook As Workbook
Dim fso As Object, bSaveOK As Boolean, i_attempt As Integer
Dim File_Name As Variant, File_Name_Saved As String
Set fso = CreateObject("Scripting.FileSystemObject")
For i_attempt = 1 To 2
File_Name = Application.GetSaveAsFilename( _
InitialFileName:=V_WBNameOutPut, _
filefilter:="Excel Files(*.xlsx),*.xlsx,Excel-Macro Files (*.xlsm),*.xlsm", _
Title:="Please choose a Folder")
If File_Name = False Then Exit Sub
bSaveOK = (fso.getbasename(File_Name) = V_WBNameOutPut)
If Not bSaveOK And i_attempt = 1 Then
MsgBox "Please do not change the File name from " & V_WBNameOutPut _
& vbCrLf & i_attempt & "/2 Attempt"
Else
Exit For
End If
Next
' create workbook and save
If bSaveOK Then
Set NewWorkBook = Workbooks.Add
Application.DisplayAlerts = False
NewWorkBook.SaveAs File_Name, ConflictResolution:=True
Application.DisplayAlerts = True
End If
End Sub

Subscript out of range Error in Copying cell value

I am using this script. I am getting Subscript out of range Error in the line below indicated with the comment
'This is the section to customize, replace with your own action code as needed**
I am trying to copy a cell value E3 present in sheet called One Pager to the sheet in file SUMMARY1.xlsm
I am getting the result but I do get the out of range error. No sure what is happening. The code looks for cell E3 in One Pager instances in multiple files.
The folder path = C:\Users\guhaka\OneDrive - Danone\Documents\Portfolio Optimization\rTAM Presentation\Dossier\
Sub Something() '‹~~ Added this to indent the code. Please change to real name
Dim fName As String, fPath As String, fPathDone As String
Dim LR As Long, NR As Long
Dim wbData As Workbook, wsMaster As Worksheet
'Setup
Application.ScreenUpdating = False 'speed up macro execution
Application.EnableEvents = False 'turn off other macros for now
Application.DisplayAlerts = False 'turn off system messages for now
Set wsMaster = ThisWorkbook.Sheets("Master") 'sheet report is built into
With wsMaster
If MsgBox("Clear the old data first?", vbYesNo) = vbYes Then
Cells.Select
Selection.UnMerge
.UsedRange.Offset(1).EntireRow.Clear
NR = 2
Else
NR = .Range("A" & .Rows.Count).End(xlUp).Row + 1 'appends data to existing data
End If
'Path and filename (edit this section to suit)
fPath = "C:\Users\guhaka\OneDrive - Danone\Documents\Portfolio Optimization\rTAM Presentation\Dossier\" 'remember final \ in this string
fPathDone = fPath & "Imported\" 'remember final \ in this string
On Error Resume Next
MkDir fPathDone 'creates the completed folder if missing
On Error GoTo 0
fName = Dir(fPath & "*.xlsm*") 'listing of desired files, edit filter as desired
'Import a sheet from found files
Do While Len(fName) > 0
If fName <> ThisWorkbook.Name Then 'don't reopen this file accidentally
Set wbData = Workbooks.Open(fPath & fName) 'Open file
'This is the section to customize, replace with your own action code as needed
Sheets("One Pager").Range("E3").Copy
wbData.Close False 'close file
Workbooks("SUMMARY1.xlsm").Activate
ActiveSheet.Range("E3").Select
ActiveSheet.Paste
Name fPath & fName As fPathDone & fName 'move file to IMPORTED folder
fName = Dir 'ready next filename
End If
Loop
End With
ErrorExit: 'Cleanup
ActiveSheet.Columns.AutoFit
Application.DisplayAlerts = True 'turn system alerts back on
Application.EnableEvents = True 'turn other macros back on
Application.ScreenUpdating = True 'refreshes the screen
End Sub
Here's how to avoid the overwrite:
'...
'...
'Import a sheet from found files
Do While Len(fName) > 0
If fName <> ThisWorkbook.Name Then 'don't reopen this file accidentally
Set wbData = Workbooks.Open(fPath & fName) 'Open file
'copy E3 to the next empty cell on the summary sheet
' (adjust sheet/workbook as needed)
wbData.Sheets("One Pager").Range("E3").Copy _
ThisWorkbook.Sheets("Summary").cells(Rows.Count, "E").End(xlUp).offset(1, 0)
wbData.Close False 'close file
Name fPath & fName As fPathDone & fName 'move file to IMPORTED folder
fName = Dir 'ready next filename
End If
Loop
'...
'...

Update source to all excel links in word vba

I am trying to update the source to all the links in a word report by using a macro in word VBA. I want to be able to offer a dialog box to user then they select file and it replaces current source in all links in the word doc. The code i have below works but really slowly. I also seem to have to open excel in the background or the links wont work? not sure why this is??
It seems to go through eack link in tuen. Is there a way to globally change all the links at the same time possibly using find and repalce? please any help is greatly appreciated! I need this for a reprot in work and so i need to find a solution as soon as possible.
Private Sub CommandButton1_Click()
Dim OldFile As String
Dim xlsobj As Object
Dim xlsfile_chart As Object
Dim dlgSelectFile As FileDialog 'FileDialog object '
Dim thisField As Field
Dim selectedFile As Variant
'must be Variant to contain filepath of selected item
Dim newFile As Variant
Dim fieldCount As Integer '
Dim x As Long
On Error GoTo LinkError
'create FileDialog object as File Picker dialog box
Set dlgSelectFile = Application.FileDialog
(FileDialogType:=msoFileDialogFilePicker)
With dlgSelectFile
.Filters.Clear 'clear filters
.Filters.Add "Microsoft Excel Files", "*.xls, *.xlsb, *.xlsm,
*.xlsx" 'filter for only Excel files
'use Show method to display File Picker dialog box and return user's
action
If .Show = -1 Then
'step through each string in the FileDialogSelectedItems collection
For Each selectedFile In .SelectedItems
newFile = selectedFile 'gets new filepath
Next selectedFile
Else 'user clicked cancel
Exit Sub
End If
End With
Set dlgSelectFile = Nothing
' update fields
Set xlsobj = CreateObject("Excel.Application")
xlsobj.Application.Visible = False
Set xlsfile_chart = xlsobj.Application.Workbooks.Open(newFile,
ReadOnly = True)
Application.ScreenUpdating = False
With xlsobj.Application
.calculation = xlcalculationmanual
.enableevents = False
End With
fieldCount = ActiveDocument.Fields.Count
For x = 1 To fieldCount
With ActiveDocument.Fields(x)
If .Type = 56 Then
.LinkFormat.SourceFullName = newFile
End If
End With
Next x
With xlsobj.Application
.calculation = xlcalculationmanual
.enableevents = True
End With
Application.ScreenUpdating = True
MsgBox "Data has been sucessfully linked to report"
'clean up
xlsfile_chart.Close SaveChanges:=False
Set xlsfile_chart = Nothing
xlsobj.Quit
Set xlsobj = Nothing
Exit Sub
LinkError:
Select Case Err.Number
Case 5391 'could not find associated Range Name
MsgBox "Could not find the associated Excel Range Name " & _
"for one or more links in this document. " & _
"Please be sure that you have selected a valid " & _
"Quote Submission input file.", vbCritical
Case Else
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical
End Select
' clean up
Set xlsfile_chart = Nothing
xlsobj.Quit
Set xlsobj = Nothing
End Sub
Dim FolderName As String
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
On Error Resume Next
FolderName = .SelectedItems(1)
On error go to 0
End With
If FolderName = "" Then
Exit Sub
End If
'Continue with code using FolderName as your source path
Hopefully this will serve as a good starting point for you. This will get you the path of the source folder and store it in FolderName. You can then build your link using:
CompletePath = FolderName + [FileNameGoesHere]
(Don't forget to make sure your FolderName has a "\" on the end, else the path will be incorrectly formatted, if it doesn't you can add it in or perform a check to ensure it is present on the end of the FolderName string

When pasting data from one workbook to another, overalpping data or data not showing at all.

I'm new to VBA so not exactly sure how this all works but I've got the jist.
I am trying to import data from multiple workbooks into one workbook that is created by the program. I have got the main importing done correctly (although not effeciently) but then one of three things happens: The data is imported into correct places and is fine, the data overlaps after the first set, or only the first set of data is transferred. I just can't work out why!
Do
Filename = InputBox("What is the full path and name of the file?")
Workbooks.Open (Filename)
data_range = InputBox("What is the cell range of the wanted data in the original file? If this is the first set of data, include the titles for reference")
ActiveSheet.Range(data_range).Select
Selection.Copy
ActiveWorkbook.Close
If first = True Then
ActiveSheet.Range("b2").Select
End If
If first = False Then
ActiveSheet.Range("b" & (difference + 3)).Select
End If
ActiveSheet.Paste
ActiveSheet.Range("a1").Select
again = MsgBox("Would you like to import another set of data?", 4)
Call start_cell(range_of_cells, data_range)
first = False
Loop Until again = vbNo
That was the main program. The sub-procedure start_cell is below:
range_of_cells = Split(data_range, ":")
NUMBERS(0) = Right(range_of_cells(0), 2)
NUMBERS(1) = Right(range_of_cells(1), 2)
check = IsNumeric(NUMBERS(0))
If check = False Then
'wrong
End If
check = IsNumeric(NUMBERS(1))
If check = False Then
'wrong
End If
difference = (NUMBERS(1) - NUMBERS(0)) + difference
Any help would be awesome. Also if there are any more effecient ways that'd be great.
This is a sketch of what could work, check it, run it, customize it and let me know if something isn't working or I misunderstood your question.
Function GetFolder(ByVal sTitle As String) As String
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = sTitle
.Show
On Error Resume Next
GetFolder = .SelectedItems(1)
On Error GoTo 0
End With
End Function
Sub Main()
Const START_ADDR As String = "A17"
Dim sPath As String, sFile As String
Dim wbLoop As Workbook
Dim wsLoop As Worksheet, wsConsolidate As Worksheet
Dim rData As Range
'save current sheet in variable (change if required)
wsConsolidate = ActiveSheet
'ask for folder
sPath = GetFolder("Select the folder where your files reside.")
'if none provided quit
If sPath = "" Then
MsgBox "No folder selected."
Exit Sub
End If
'get all excel files from specified folder
sFile = Dir(sPath & "\*.xls*")
Do Until sFile = ""
'open file
Set wbLoop = Workbooks.Open(sPath & "\" & sFile)
Set wsLoop = wbLoop.Sheets(1) 'change if other
'copy data out
Set rData = wsLoop.Range(START_ADDR).CurrentRegion
'if the data has headers uncomment below
'Set rData = rData.Offset(1, 0).Resize(rData.Rows.Count)
rData.Copy wsConsolidate.Cells(wsConsolidate.Rows.Count, "B").End(xlUp).Offset(1, 0)
'close file without saving
wbLoop.Close False
'loop through files
sFile = Dir
Loop
End Sub

Iterate through spreadsheets in a folder and collect a value from each

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

Resources