Macro (VBA) in Excel is failing on colleagues PC but works on mine when colleague is logged in - vba

I'm developing VBA tools to automate a series of long winded administration tasks, the code runs fine in the following circumstances.
When I am logged into my PC
When my colleague is logged into my PC
When I am logged into my colleagues PC
However it fails to complete correctly, when my colleague runs it on her PC.
The specific area it is failing in is:
'creates 2 dims for location of the two files that need opening based on the critera set on the home page
Dim newdata As String
newdata = Range("f11").Value
Dim olddata As String
olddata = Range("f12").Value
Dim fileextension As String
fileextension = Range("f14").Value
Dim fulllocationolddata As String
fulllocationolddata = Range("f13") & olddata & fileextension
Dim fulllocationnewdata As String
fulllocationnewdata = Range("f13") & newdata & fileextension
'open file containing OLDDATA c&p previous days data to the conversion tool
'then shuts the old data workbook
Workbooks.Open Filename:=fulllocationolddata
Workbooks(olddata).Activate
Worksheets("sheet1").Select
Range("A1").CurrentRegion.Copy
Workbooks("Stockfile Conversion Tool.xlsm").Activate
Sheets("OLD STOCK").Activate
Range("A3").Select
Selection.PasteSpecial
Workbooks(olddata).Activate
Worksheets("sheet1").Select
Workbooks(olddata).Close SaveChanges:=False
The final line (Workbooks(olddata).Close SaveChanges:=False) does not shut the workbook, then later in the macro I open another workbook of the same name but as it's already open it just activates the window and the rest of the code falls apart.
If anyone has any ideas where I'm going wrong it would be appreciated.
Thanks in advance for your assistance
Plan303

Making my comments to an answer here:
Whether Workbooks("Name of the Workbook") is working or not depends on the settings in System control - Folder Options - View - [ x ] Hide extensions for known file types.
If this is set, then Excel's file extensions .xlsx, .xlsm, ... are not visible in Explorer or other file listings. Only the file names of the Excel files are visible. If so, then Workbooks("Name of the Workbook") will work.
If Hide extensions for known file types is not set, then Excel's file extensions .xlsx, .xlsm, ... are visible in Explorer or other file listings. If so, then Workbooks("Name of the Workbook") will not work. Then only Workbooks("Name of the Workbook.xlsx"), giving the name and the extension, will work.
But Workbooks("Name of the Workbook.xlsx") will also work if Hide extensions for known file types is set. So using the full name inclusive extension should be preferred.
So for the concrete question:
If olddata only contains the name of the workbook and not the file extension then Workbooks(olddata) will only work if Hide extensions for known file types is set in Folder Options. It will fail, if that option is not set and the file extensions are visible in Explorer. But Workbooks("Stockfile Conversion Tool.xlsm") will always work independent of whether Hide extensions for known file types is set or not. So Workbooks(olddata & fileextension) should also always work if olddata only contains the name of the workbook and fileextension contains .xlsx for example.

Related

VBA not working in 2016 as it did in 2013: suggested file name (InitialFileName) not showing up

I have a code to export an Excel tab and save it as a new file with a preset file name. The user has the option to review the file name before saving. This is what I have been using:
InitialName = SaveString & UniqueString
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName)
If fileSaveName <> False Then
Export.SaveAs (fileSavename)
End If
SaveString is the save folder, and UniqueString is the specific file name, which changes each month. The user clicks Export, the tab is prepared, and the Save As folder pops up in the correct folder with the suggested file name. As long as the user hits "Save," then the exported tab is saved in the SaveString folder with the UniqueString name (with .xlsx already included in UniqueString).
Since upgrading to Office 2016, the UniqueString suggested file name no longer shows up. The Save As pop-up still opens in the SaveString folder, but there is no suggested file name. If the user isn't careful to manually add .xlsx to the end of the file name, then the file type is an unusable "File."
I've opened Excel 2013 in a virtual setting and run the code side-by-side, and it works perfectly in the older version. Does anyone have insight as to why this change happened, and how to correct it?
It appears that you now need to include a file filter that matches the initial name you provide, so the following will possibly work:
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
FileFilter:="Excel Files (*.xlsx),*.xlsx")

Excel VBA to open Sharepoint folder and create list of hyperlinks for files within

Prior to being asked to migrate to SharePoint, I was using a collection of .xlsm files to set project teams up to manage projects. My Project Manager file included a macro that would go to a designated folder and create hyperlinks for all current project files. I've saved the collection of .xlsm files on SharePoint, but when I run the macro below (which I found here - Thank you!), I receive an error related to the "Set xFolder = xFSO.GetFolder(xPath)" line. Any help would be great. I've read several posting that may have the answer and tried several adjustments to the code, with no luck.
Sub Create_Hyperlinks_for_all_Current_Projects()
Range("B8:D38").Clear
MsgBox "Once you click OK, an explorer box will appear. Select the folder
containing all the CSTPs and then click OK again. HINT: The folder
containing all the CSTPs should be in the same folder this document was in
and should be called ''CSTPs''. Links to all CSTPs will then appear in the
white box on the Manager Menu."
Dim xFSO As Object
Dim xFolder As Object
Dim xFile As Object
Dim xFiDialog As FileDialog
Dim xPath As String
Dim I As Integer
Set xFiDialog = Application.FileDialog(msoFileDialogFolderPicker)
With xFiDialog
.InitialFileName = ThisWorkbook.Path
End With
If xFiDialog.Show = -1 Then
xPath = xFiDialog.SelectedItems(1)
End If
Set xFiDialog = Nothing
If xPath = "" Then Exit Sub
Set xFSO = CreateObject("Scripting.FileSystemObject")
Set xFolder = xFSO.GetFolder(xPath)
For Each xFile In xFolder.Files
I = I + 2
ActiveSheet.Hyperlinks.Add Cells(I + 6, 2), xFile.Path, , , xFile.Name
Next
End Sub
I hope you find the following notes helpful.
They summarize the outcomes from several weeks of frustration.
If you are using SP365,
then the filesystemobject
no longer works very well, if at all.
I had hundreds of macros dependent on the FSO.
These have all worked great up until my organization migrated to SP365 :o(
Now they only work if I manually click
the Open Explorer button, in SP, first.
Opening Explorer provides Win Explorer with the required permissions to access SP.
This in turn provides the FSO with the required permissions to access SP.
But...in my case...FSO only works for a while.
For my first work around...
I rolled out a prototype app, which used a macro to automate
opening IE, opening Win Explorer and initializing permissions for the FSO
All worked great on my machine, for about an hour,
then some kind of timeout took me back to square one.
Colleagues on other machines experienced a range of FSO behaviours.
From all working ok. To having to rerun the connection macro every 30 seconds.
To nothing working at all.
I then invested time trying to update macros to connect to SP as a network drive.
Again, this is a process that I have used for years, up until migration to SP365.
Again, success connecting to SP365 seems to be very machine dependent.
In the end...with respect to my own requirements...
My work around was to create an SP view that lists all files.
Then use the Export to Excel option in SP to create an Excel data query.
Then copy the query into an Excel file that I refer to as Config.xlsx.
Then use Excel RefreshAll to update the list of files, each time a list is required.
Its not very elegant...but, it works ;o)
As I say....I hope this helps you / someone.
Feel free to connect on LinkedIn if you require any followup advice.
Peter,
LinkedIn name DrPeterEHSmee

Activate window of another Visio instance

Currently I have a file name stored in string called filename. The file stored in the string is currently open. Issue is, this file could some times be opened in another instance of Visio.
I want to activate the file that is stored in filename string
My current method does not capture this - The code below only checks if the filename exists among the current/one instance of Visio.
For Each objDoc In objVisio.Documents
If objDoc.Name = filename Then
objDoc.activate
Exit for
End If
Next
How can I activate this file to bring it forward?
windows(filename & " - Microsoft Visio").activate
is not working either
I've tried
Dim objVisio as Visio.Application
Set objVisio = GetObject(filename).Application
which isn't working (maybe due to filename string only having the file name and not the entire file path as well)
Any other brute force methods available out there?
Any help is appreciated!
Try something like this:
objVisio.Application.Caption
Or
AppActivate "Microsoft Visio"
I guess another option is to look into this: https://msdn.microsoft.com/en-us/library/office/ff766749.aspx
I haven't worked extensively with Visio in VBA, so I am interested to see the true answer here.

Is there a way to save all hyperlinked documents in excel?

I know this question has been answered before, but the problem I'm facing is a bit different, and this is why I'm asking for your help :)
So, I'm working with multiple excel files that contain multiple hyperlinks that lead to documents such as Excel files, PDFs, DOCs and sometimes even images. The problem with these hyperlinks is that they are not leading to a "normal" website, but to a special internal software, that in its turn links to a local address on my computer that contatins the desired file. That means that there is no direct link that could be grabbed with a simple VBA code.
Let's have an example, assuming the internal software name is "John":
I see in the Excel documents this link: John://3434545345/345345345
When I click on it, it opens the file, which is located, for example, in: C:/local/Cutekitten.pdf
After this long intro, my question is: Is there a way to automate the process of saving each document, instead of manually opening it and saving it? Could it be solved with a VBA code? Or does is require a different approach? I was actually thinking to bypass this problem by finding a way to open all hyperlinks at once with VBA, and then maybe find some code (not VBA?) that saves all open documents.
P.S Please keep in mind that I can't download EXE files or any other "suspicious" files due to workplace restrictions.
Any help will be much appreciated,
Thanks! :)
You may try this
'''
Input: test.xlsx
name link
1 location/file1.jpg
2 location/file2.xlsx
3 location/file3.pdf
4 location/file4.mp4
'''
from openpyxl import load_workbook
wb = load_workbook('test.xlsx')
print wb.get_sheet_names()
# ['Sheet 1', 'Sheet 2', 'Sheet 3']
ws1 = wb['Sheet 1']
## alternate -> worksheet2 = wb2.get_sheet_by_name('Sheet2')
import urllib
import os
## Result directory
directory = 'result'
if not os.path.exists(directory):
os.makedirs(directory)
for row in ws1:
if '.exe' in row[1].value:
continue
print row[0].value, '\t', row[1].value
urllib.urlretrieve (row[1].value, directory+'/'+row[1].value)
'''
Output:
Table 1 None
None None
name link
1 location/file1.jpg
2 location/file2.xlsx
3 location/file3.pdf
4 location/file4.mp4
'''
Sub PathsText()
Dim List(), Path As String
Dim i, x As Integer
Dim s As InlineShape
Dim fso As FileSystemObject, ts As TextStream
Set fso = New FileSystemObject
Set ts = fso.OpenTextFile("C:\MyFolder\List.txt", 8, True)
With ts
.WriteLine (ActiveDocument.InlineShapes.Count)
End With
For Each s In ActiveDocument.InlineShapes
Path = s.LinkFormat.SourcePath & "\" _
& s.LinkFormat.SourceName
With ts
.WriteLine (Path)
End With
Next s
End Sub
I guess the important part is if "Path = s.LinkFormat.SourcePath" works.
If so, if you have a ton of excel files to do it for, I'd put those (the ones with the links) in one folder. I'd make a new empty workbook with one button on a single sheet to call code. The button would "For Each workbook in directory, For Each sheet in workbook, For Each link on sheet" add source path to a text file.
Once you had a list of paths the next step would be obvious. I wish I had demo code, but I migrated to c# years ago. My monstrously slow cell-by-cell search, modify and graph inventions threatened to bury me.

VBA fails to find a file

I have a VBA script used to process Word documents. The first thing the program does is to create an index of the documents in a defined set of folders. It then goes through the list processing each of the indexed documents.
The problem I am having is that it will sometimes decide that a particular document cannot be found, even though it previously indexed the document and a quick spot check shows the document to be in the correct place.
Can anyone shed some light on why VBA should display this behaviour?
The script is using the Dir$ function to index the files, and the Documents.Open function to open each word document for processing.
Sample code:
ChangeFileOpenDirectory (folderName)
inputFileName = Dir$(folderName & "*.doc")
Do While inputFileName <> ""
... call various functions here ...
inputFileName = Dir$
Loop
One of the functions called in the block has the following line:
Set currentDoc = Documents.Open(fileName:=docFileName, AddToRecentFiles:=False, Visible:=False)
This is the point at which the code is failing.
One of the most annoying things I have found is that recent files links are returned as the files themselves with Dir. You can use the FileSystemObject to check the file type.
I copy/paste your code and it works correctly.
However, it leaves all the files open (and hidden), and when you run it in another directory, additional files are opened and added to the open projects (take a look in the VBA editor).
My only guess is that after a while you're hitting the maximum allowable number of open files.
Try adding
currentdoc.Close
just before
inputFileName = Dir$
A few reasons, some duplicated from other answers:
If the path+ filename is long enough ... (you already answered in a comment)
If you are writing new files to same directory, Dir$ may get corrupted (happened to me)
If you have filenames with non-std chars (ex. "#")
Files locked by other processes
Files deleted while the macro is running
You may also try this code ...
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(file) Then ....
First enable the Microsoft Scripting reference in the VBE