I am having trouble getting this macro to work. I am working on a Windows 10 computer with Office 2013. The code was not written by me and I have limited knowledge in VB. The marco is supposed to update a a word document's links by mirroring how the the previous word document was linked. Below is the code, if anyone could help that would be great.
Sub relinking()
Dim oriacro As String
Dim taracro As String
Dim path As String
oriacro = InputBox(Prompt:="please enter the original agency acronym.", Title:="ENTER THE ORIGINAL AGENCY ACRONYM")
taracro = InputBox(Prompt:="please enter the target agency acronym.", Title:="ENTER THE TARGET AGENCY ACRONYM")
path = InputBox(Prompt:="please enter the target path.", Title:="ENTER THE TARGET PATH")
Excel.Application.Quit
'close all the excel files.(excel reference has to be activated in tool->reference'
For x = 1 To ActiveDocument.Fields.Count
'the program runs over all the linked fields'
If Left(ActiveDocument.Fields(x).LinkFormat.SourceNam e, Len(oriacro)) = oriacro Then
'read all the fields that has "original agency acronym" in the beginning of its linked excel files.'
ActiveDocument.Fields(x).LinkFormat.SourceFullName = path & "\" & taracro & "_" & Right(ActiveDocument.Fields(x).LinkFormat.SourceNa me, Len(ActiveDocument.Fields(x).LinkFormat.SourceName ) - InStr(ActiveDocument.Fields(x).LinkFormat.SourceNa me, "_"))
'Assign the fields with new links that are created from combining the "target path" ,"target agency acronym", and the parts of the names right after the original acronyms of the original linked file names.'
Else
'Leave other linked fields as they are.'
End If
Next x
MsgBox ("All Fields have been relinked!")
End Sub
1) few typos in the above code which might just be formatting on StackOverflow: .SourceNam e a couple times. Also in the function which makes the new path:
Right(ActiveDocument.Fields(x).LinkFormat.SourceNa me, Len(ActiveDocument.Fields(x).LinkFormat.SourceName ) - InStr(ActiveDocument.Fields(x).LinkFormat.SourceNa me, "_")).
Also add a string variable and catch one of them in a msgbox to test:
If Left(ActiveDocument.Fields(x).LinkFormat.SourceNam e, Len(oriacro)) = oriacro Then
'read all the fields that has "original agency acronym" in the beginning of its linked excel files.'
str = ActiveDocument.Fields(x).LinkFormat.SourceName 'Dim str variable above if necessary
ActiveDocument.Fields(x).LinkFormat.SourceFullName = path & "\" & taracro & "_" & Right(str, InStrRev(str, "_")-1)
'Assign the fields with new links that are created from combining the "target path" ,"target agency acronym", and the parts of the names right after the original acronyms of the original linked file names.'
msgbox ActiveDocument.Fields(x).LinkFormat.SourceFullName 'does this message show the proper path??
Else
'Leave other linked fields as they are.'
End If
ActiveDocument.Fields.Update
Related
I'm trying to create a little program thats introduce some prefixes into the name of the files that found at a folder.
The names of files are listed at a Listbox1 and the prefixes are choosed at a several Comboboxes.
This names of the Listbox1 with the choosed prefixes of the Comboboxes are moved to a Listbox2 pressing a buttom ">>>".
When all of new names are ready at this Listbox2 will be press a buttom "Rename" and the names of files at the folder will be changed according fixed at the Listbox2.
All of the Userform is already programmed. I have just problems to build the code for the buttom "Rename".
In others Words, taking the stipulate names of the Listbox2 and changing the names at the respective files showed before at the Listbox1.
How i can read the new names of files from a Listbox and introduce to the respective name of file?
Userform Screenshot
Code:
Sub cmdMoveSelLeft_Click()
'Variable Declaration
Dim iCnt As Integer
'Move Selected Items from Listbox1 to Listbox2
For iCnt = 0 To Me.ListNewFiles.ListCount - 1
If Me.ListNewFiles.Selected(iCnt) = True Then
Dim changedName As String
changedName = Me.ComboBoxKategorie.Value + "_" + Me.ComboBoxTyp.Value + "_" + Me.ListNewFiles.List(iCnt)
Me.ListChangedFiles.AddItem changedName
End If
Next
For iCnt = Me.ListNewFiles.ListCount - 1 To 0 Step -1
If Me.ListNewFiles.Selected(iCnt) = True Then
Me.ListNewFiles.RemoveItem iCnt
End If
Next
ComboBoxKategorie = ""
ComboBoxTyp = ""
TextBoxEXX = ""
TextBoxUX = ""
TextBoxTrakt = ""
TextBoxGebaude = ""
TextBoxSpecific = ""
Sub cmdRename_Click()
Dim Msg = 'Möchten Sie fortfahern?'
Response = MsgBox(Msg, Style, Title, Help, Ctxt)
If Response = vbYes Then ' User chose Yes.
~?????????????~
MsgBox "Die Namen sind angepasst" & vbCrLf
Unload Me
End If
End Sub
Use the Name keyword like
Name "C:\Post IN\BEISPEIL_SAN_SP_U2" As "C:\Post IN\AUS_BPH_BEISPEIL_SAN_SP_U2"
Of course you won't use string literals like that, but I can't tell where you have the old name and the new name. Generally, the syntax is
Name "FullPathOfExistingName" As "FullPathOfNewName"
I know I've seen references to this issue before, but I have tried several of the suggestions and I am still getting the error. I have a workbook that assembles data from another book and generates a report. I then want to make a new workbook, copy the report information into the new book, save the new book and close it, and then move on to the next report. It should do this around 10 times. In the part of my code where I am copying and pasting the sheets, I am getting an error
Error -2147417848 Automation error The object invoked has
disconnected from its clients
I have checked other postings about this error, and tried the suggested solutions without any results. the interesting thing is that sometimes it will make it through 5 cycles of code before breaking, sometimes only 2. The only consistency is that it always breaks in the same place
fromBook.Sheets("Report").Copy Before:=newBook.Sheets("Sheet1")
I have option Explicit at the top of the module, and I have checked to make sure that there are not any globals inside of the sub it is breaking in. That being said, It's entirely possible I have overlooked something. I also put a "timer" in at one point to make sure that the excel sheets were not walking over each other.
I could really use the help!
Here is my sub's code:
Sub CreateAndSave(ByRef Reg As Integer, ByVal j As Integer)
Dim fromBook As Workbook
Dim fromSheet As Worksheet
Dim newBook As Workbook
Dim fileExists As Boolean
Dim i As Integer
Dim Holder As Integer
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set fromBook = Application.Workbooks("Region_Audit_Report")
Set newBook = Workbooks.Add
With newBook
.SaveAs Filename:="G:\DataTeam\ExcelDev\Audit Report\Region Workbooks\Region" & Reg & " " & Month(Date) & "-" & Day(Date) & "-" & Year(Date) & ".xlsx" _
, FileFormat:=xlOpenXMLWorkbook
End With
Set newBook = Application.Workbooks("Region" & Reg & " " & Month(Date) & "-" & Day(Date) & "-" & Year(Date) & ".xlsx")
fromBook.Sheets("Report").Copy Before:=newBook.Sheets("Sheet1")
fromBook.Sheets("MonthData").Copy After:=newBook.Sheets("Report")
newBook.Sheets("MonthData").Range("A1") = "Month"
newBook.Sheets("MonthData").Range("B1") = "Store#"
newBook.Sheets("MonthData").Range("C1") = "District"
newBook.Sheets("MonthData").Range("D1") = "Region"
newBook.Sheets("MonthData").Range("E1") = "Due Date"
newBook.Sheets("MonthData").Range("F1") = "Comp Date"
newBook.Sheets("MonthData").Range("G1") = "# of Errors"
newBook.Sheets("MonthData").Range("H1") = "Late?"
newBook.Sheets("MonthData").Range("I1") = "Complete?"
newBook.Sheets("MonthData").Range("A1:I1").Interior.ColorIndex = 43
newBook.Save
newBook.Close
Application.DisplayAlerts = True
End Sub
I have had this problem on multiple projects converting Excel 2000 to 2010. Here is what I found which seems to be working. I made two changes, but not sure which caused the success:
1) I changed how I closed and saved the file (from close & save = true to save as the same file name and close the file:
...
Dim oFile As Object ' File being processed
...
[Where the error happens - where aArray(i) is just the name of an Excel.xlsb file]
Set oFile = GetObject(aArray(i))
...
'oFile.Close SaveChanges:=True - OLD CODE WHICH ERROR'D
'New Code
oFile.SaveAs Filename:=oFile.Name
oFile.Close SaveChanges:=False
2) I went back and looked for all of the .range in the code and made sure it was the full construct..
Application.Workbooks("workbook name").Worksheets("worksheet name").Range("G19").Value
or (not 100% sure if this is correct syntax, but this is the 'effort' i made)
ActiveSheet.Range("A1").Select
I have just met this problem today: I migrated my Excel project from Office 2007 to 2010. At a certain point, when my macro tried to Insert a new line (e.g. Range("5:5").Insert ), the same error message came. It happens only when previously another sheet has been edited (my macro switches to another sheet).
Thanks to Google, and your discussion, I found the following solution (based on the answer given by "red" at answered Jul 30 '13 at 0:27): after switching to the sheet a Cell has to be edited before inserting a new row. I have added the following code:
'=== Excel bugfix workaround - 2014.08.17
Range("B1").Activate
vCellValue = Range("B1").Value
Range("B1").ClearContents
Range("B1").Value = vCellValue
"B1" can be replaced by any cell on the sheet.
You must have used the object, released it ("disconnect"), and used it again. Release object only after you're finished with it, or when calling Form_Closing.
I had this same problem in a large Excel 2000 spreadsheet with hundreds of lines of code. My solution was to make the Worksheet active at the beginning of the Class. I.E. ThisWorkbook.Worksheets("WorkSheetName").Activate
This was finally discovered when I noticed that if "WorkSheetName" was active when starting the operation (the code) the error didn't occur. Drove me crazy for quite awhile.
Couple of things to try...
Comment out the second "Set NewBook" line of code...
You already have an object reference to the workbook.
Do your SaveAs after copying the sheets.
The error in the below line of code (as mentioned by the requestor-William) is due to the following reason:
fromBook.Sheets("Report").Copy Before:=newBook.Sheets("Sheet1")
The destination sheet you are trying to copy to is closed. (Here newbook.Sheets("Sheet1")).
Add the below statement just before copying to destination.
Application.Workbooks.Open ("YOUR SHEET NAME")
This will solve the problem!!
I really need help. I need a VBA function to make copies of a single PDF file. For example a file with the reference/name 1, I would need an amount x of copies lets say 1 to 10. In order to avoid coping and paste 9 times and renaming them manually I am sure there must be a function to do this job. I am very basic with VBA so any help would be much appreciated.
Many Thanks
First you will need to add a reference to Microsoft Scripting Runtime in the VBA editor. Then the following will work...
Public Sub Test()
CopyFile "C:\Users\randrews\Desktop\1.gif", "C:\Users\randrews\Desktop", 10
End Sub
Public Sub CopyFile(OriginalPath As String, DestinationFolderPath, Copies As Integer)
Dim fs As New FileSystemObject
For i = 1 To Copies
OrigName = fs.GetFileName(OriginalPath) 'file name with extention e.g. 1.gif
OrigNumber = CInt(Left(OrigName, Len(OrigName) - 4)) 'file name converted to a number - this will crash if the file name contains any non numeric chars
DestName = OrigNumber + i & "." & fs.GetExtensionName(OriginalPath) 'new file name = original number + i + the file extension
fs.CopyFile OriginalPath, DestinationFolderPath & "\" & DestName
Next i
End Sub
I am particularly new to coding, not to mention VBA. After a week of really cracking down on learning VBA, I've started to get the hang of it. At the moment, I'm trying to put together a code that will pull the hyperlinks (both addresses and names) out of a word document (eventually word, excel, and power point files), and dump them into the excel file I run the code from. It also dumps the file path and name at the top of the list. I can run the code and pull links from 1 file at a time, and the code pops it out after the end of the last filled line. It will save me endless amounts of time when I have to update links.
Sub ExtractWordLinks()
'the following code gets and sets an open file command bar for word documents
Dim Filter, Caption, SelectedFile As String
Dim Finalrow As String
Filter = "docx Files (*.docx),*.docx, doc Files (*.doc),*.doc, xlsm Files (*.xlsx),*.xlsx"
Caption = "Please Select .doc, .docx, .xlsx files only, " & TheUser
SelectedFile = Application.GetOpenFilename(Filter, , Caption)
'check if value is blank if it is exit
Finalrow = Cells(Rows.Count, 1).End(xlUp).Row
If (Trim(SelectedFile) = "") Then
Exit Sub
Else
'setting up the inital word application object
Set wordapp = CreateObject("word.Application")
'opening the document that is defined in the open file dialog
wordapp.documents.Open (SelectedFile)
'ability to change wether it needs to burn cycles updating the UI
wordapp.Visible = False
'declare excel sheet
Dim xlsSheet As Excel.Worksheet
'set active sheet
Set xlsSheet = Application.ActiveSheet
Dim i As Integer
i = 1
'MsgBox (wordapp.ActiveDocument.Hyperlinks.Count)
For i = 1 To wordapp.ActiveDocument.Hyperlinks.Count
'puts the title of the document in the formatted cells
'xlsSheet.Cells(Finalrow + 1, 1).Value = wordapp.ActiveDocument.Path & "\" & wordapp.ActiveDocument.Name
'formats the file name cell to be a bit easier to discern from the listing.
Range(Cells(Finalrow + 1, 1), Cells(Finalrow + 1, 2)).Font.Bold = True
Range(Cells(Finalrow + 1, 1), Cells(Finalrow + 1, 2)).Merge
'save the links address.
xlsSheet.Cells(Finalrow + i, 1).Value = wordapp.ActiveDocument.Hyperlinks(i).Address
'save the links display text
xlsSheet.Cells(Finalrow + i, 2).Value = wordapp.ActiveDocument.Hyperlinks(i).TextToDisplay
Next
wordapp.ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
wordapp.Quit SaveChanges:=wdDoNotSaveChanges
End If
End Sub
My problem, is that when I run this code on a simple sample file with 3 or so hyperlinks in it across a single page, it returns everything exactly how I want, with the file path/name at the top and all the links in the page directly below it (address in one column, displayed text in the other). However, when I run it on one of the files I am writing this code for (a 95+ page .docx file with ~30 links), it prints out the path/file in the formatted section, and then drops 90 (90 every time) blank lines before printing out the path/file a second time, and then all the links in the document. It does it perfectly, except for the inexplicable second path/file (even there if I comment out the bit I put in) and the 90 blank entries.
Can anyone explain what's going on, or should I try to figure out a way to just bypass the issue by removing my own link code, and including a bit that removes all blank lines?
I would like to create a VB "Save As" macro for Excel that would utilize the data from cell B7,B5 and =NOW as the file name. This new file name would then be saved to a particular directory. (Ex. User clicks "Save" button. File name = (B5)ABCD_(B7)EFGH_=NOW is created and then saved to a directory of my choosing.
I have found scripts that offer some of the singular options, but have had no luck finding or creating a script of my own with these options. Any help would be greatly appreciated.
You need to substitute for the invalid characters in the filename (they can't contain / or :) with periods or something else.
Sub DateFile()
Dim str As String
str = Range("B5").Value & "ABCD_" & Range("B7").Value & "EFGH" & Now()
str = Replace(str, "/", ".")
str = Replace(str, ":", ".")
ActiveWorkbook.SaveAs (str)
End Sub
This can then be integrated into your push button code.