Excel VBA check if file exists with a twist - vba

It is hard to be specific and short in this topic, but I try my best:
Let's say we have a folder on a specific location where we get files with names for example let's use x1; x2; x3, etc.
Then we have an excel file where we have numbers in a column. ex. 1; 2; 3; etc.
I have written a script that makes it possible to click those numbers so an explorer window will pop up searching for the specific number in the folder.
For example we click the number "2", and an explorer window will pop up with the search result for "2x" in that specific folder.
The script looks like this:
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
Dim c As String
Dim backup As String
c = Target.Range
backup = "~%3D" & Left(c, 7)
If Left(c, 1) = "C" And Len(c) > 7 And Right(c, 1) = "$" Then 'this part doesn't really matter
RetVal = Shell("c:\Windows\explorer.exe ""search-ms:displayname=Search%20Results&crumb=System.Generic.String%3A" & backup & "%20kind%3A%3Dfolder&crumb=location:%5C%5Cserver%5Cbackup$", vbNormalFocus)
End If
End Sub
I wonder if it is possible somehow, to find out if there is a file that matches the search or it does not exists. What I mean is, for example if I click on the number "2" in excel, the explorer will pop up and it will show the files which names contain "x2" or it will show "No items match your search."
I would like to return this somehow to excel if we have a search result or we don't.
Even a Boolean would do the trick for me.
I can not use the ordinary check like:
If Dir(folder) = "" Then
because we can have multiple files with the same name and their name contains the date of their creation. ex. x1_02_04_2015 and we can also have an x1_05_11_2014
Thank You in advance!

You can try the following. You don't really need to use any shell functionality
Sub LoopThroughFilesWorkbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
Dim MyObj As Object, MySource As Object, file As Variant, myBool As Boolean
file = Dir("c:\testfolder\")
Do While file <> ""
Bool = False
If InStr(file, "test") > 0 Then ' you can change teh condition here to fit your criteria
myBool = True
MsgBox ("Found" & file)
End If
file = Dir
Loop
If Not myBool Then
MsgBox ("File not found")
End If
End Sub

Related

VBA Excel - run string variable as a line of code

In the aim to allow users from different countries to use my application, I would like to initialize a translation of each object in each existing userform (labels,commandbuttons,msgbox,frames, etc...) at the start of the application.
I'll write all the translation in my Languages sheet:
I've already made a first userform where the user types his login, password and selects his language.
After this step, the main userform called "Menu" will be launched.
I've already tried to type a piece of code (here below) to find the line of code, in a msgbox that I want to run (example : menu.commandbutton1.caption="Envoyer email")
Private Sub UserForm_Initialize()
' Definition of language selected during login
Set langue = Sheets("Languages").Cells.Find("chosen",
lookat:=xlWhole).Offset(-1, 0)
' Initialisation of the texts in the selected language
Dim cel As Range
Dim action As String
For Each cel In Sheets("Languages").Range("d3:d999")
If cel <> "" Then
action = cel & "=" & """" & cel.Offset(0, -2) & """"
MsgBox (action)
End If
Next cel
End Sub
I've already read some topics about this subject but those does not correspond exactly to what i would like to do.
If you have a solution, or a work around, it would be very helpful.
If you simply want different MsgBox, based on a coutry, this is probably the easiest way to achieve it. Imagine your file is like this:
Then something as easy as this would allow you to use different strings, based on the country:
Public Sub TestMe()
Dim country As String
Dim language As Long
country = "Bulgaria" 'or write "England" to see the difference
language = WorksheetFunction.Match(country, Range("A1:B1"), 0)
MsgBox (Cells(2, language))
MsgBox "The capital of " & country & " is " & (Cells(3, language))
End Sub
The idea of the whole trick is simply to pass the correct column, which is done through WorksheetFunction.Match.
Taken from an old CR post I have here, this solution pretty much mimicks .NET .resx resource files, and you can easily see how to extend it to other languages, and if I were to write it today I'd probably use Index+Match lookups instead of that rather inefficient loop - but anyway it works nicely:
Resources standard module
Option Explicit
Public Enum Culture
EN_US = 1033
EN_UK = 2057
EN_CA = 4105
FR_FR = 1036
FR_CA = 3084
End Enum
Private resourceSheet As Worksheet
Public Sub Initialize()
Dim languageCode As String
Select Case Application.LanguageSettings.LanguageID(msoLanguageIDUI)
Case Culture.EN_CA, Culture.EN_UK, Culture.EN_US:
languageCode = "EN"
Case Culture.FR_CA, Culture.FR_FR:
languageCode = "FR"
Case Else:
languageCode = "EN"
End Select
Set resourceSheet = Worksheets("Resources." & languageCode)
End Sub
Public Function GetResourceString(ByVal resourceName As String) As String
Dim resxTable As ListObject
If resourceSheet Is Nothing Then Initialize
Set resxTable = resourceSheet.ListObjects(1)
Dim i As Long
For i = 1 To resxTable.ListRows.Count
Dim lookup As String
lookup = resxTable.Range(i + 1, 1)
If lookup = resourceName Then
GetResourceString = resxTable.Range(i + 1, 2)
Exit Function
End If
Next
End Function
The idea is, similar to .NET .resx files, to have one worksheet per language, named e.g. Resources.EN and Resources.FR.
Each sheet contains a single ListObject / "table", and can (should) be hidden. The columns are basically Key and Value, so your data would look like this on sheet Resources.EN:
Key Value
menu.caption Menu
menu.commandbutton1.caption Send email
menu.commandbutton1.controltiptext Click to send the document
And the Resources.FR sheet would have a similar table, with identical keys and language-specific values.
I'd warmly recommend to use more descriptive names though; e.g. instead of menu.commandbutton1.caption, I'd call it SendMailButtonText, and instead of menu.commandbutton1.controltiptext, I'd call it SendMailButtonTooltip. And if your button is actually named CommandButton1, go ahead and name it SendMailButton - and thank yourself later.
Your code can then "localize" your UI like this:
SendMailButton.Caption = GetResourceString("SendMailButtonText")
The Resources.Initialize procedure takes care of knowing which resource sheet to use, based on Application.LanguageSettings.LanguageID(msoLanguageIDUI) - and falls back to EN, so if a user has an unsupported language, you're still showing something.

Ammend code to include drop down selection instead of type-in prompt

I have the following code which prompts the user which open file/window to switch to. I am using this to get around the fact the name of my dependent data file is changing on a daily basis. The following code works. However, instead of asking in the prompt box to type the name of the file to switch to, I would like for it to recognize the open files and give me a drop down or some sort of selection to choose from to just select the file I want to switch to.
Anybody know how to do that?
Sub switch()
Dim i As Integer
Dim n As Integer
Dim s As String
Dim t As Variant
n = Windows.Count
s = "Pick From:"
For i = 1 To n
s = s & Chr(10) & Windows(i).Caption
Next
t = Application.InputBox(prompt:=s, Type:=2)
If t = False Then
Exit Sub
End If
Windows(t).Activate
End Sub

How to embed large (max 10Mb) text files into an Excel file

What is the best way to store a large text file (max 10Mb) in an Excel file?
I have a couple of requirements:
It has to be embedded so that the excel file can be moved and sent to a different computer and all the text files will follow.
It needs to be done from a macro.
And a macro needs to be able to read the file contents after it has been embedded.
I already tried to store it by breaking the text into several chunks enough small to fit into a cell (~32 000 chars), but it didn't work. After my macro had inserted the first 150 000 characters it gave me an "Out of Memory" error.
I remember seeing one web page with a couple of options for this I but cannot find it anymore. Any suggestions are most welcome. I will try them out if you are not sure if it works or not.
It would likely be best to simply save the .txt file alongside the Excel file, and have the macro pull the text as needed from that folder. To read more on importing files see this:
http://answers.microsoft.com/en-us/office/forum/office_2010-customize/vba-code-to-import-multiple-text-files-from/525bd388-0f7d-4b4a-89f9-310c67227458
Keeping the .txt within the Excel file itself is not necessary and will likely make it harder to transfer files in the long run. For example, if you cannot e-mail a file larger than 10MB, then you can simply break your .txt file in half and e-mail separately - using a macro which loads the text into Excel locally.
Very simple CustomXMLPart example:
Sub CustomTextTester()
Dim cxp1 As CustomXMLPart, cxp2 As CustomXMLPart
Dim txt As String
'read file content
txt = CreateObject("scripting.filesystemobject").opentextfile( _
"C:\_Stuff\test.txt").readall()
'Add a custom XML part with that content
Set cxp1 = ThisWorkbook.CustomXMLParts.Add("<myXMLPart><content><![CDATA[" & txt _
& "]]></content></myXMLPart>")
Debug.Print cxp1.SelectSingleNode("myXMLPart/content").FirstChild.NodeValue
End Sub
Consider the method shown below. It uses Caption property of Label object located on a worksheet for data storage. So you can create a number of such containers with different names.
Sub Test()
Dim sText
' create special hidden sheet for data storage
If Not IsSheetExists("storage") Then
With ThisWorkbook.Worksheets.Add()
.Name = "storage"
.Visible = xlVeryHidden
End With
End If
' create new OLE object TypeForms.Label type as container
AddContainer "test_container_"
' read text from file
sText = ReadTextFile("C:\Users\DELL\Desktop\tmp\tmp.txt", 0)
' put text into container
PutContent "test_container_", sText
' retrieve text from container
sText = GetContent("test_container_")
' show length
MsgBox Len(sText)
' remove container
RemoveContainer "test_container_"
End Sub
Function IsSheetExists(sSheetName)
Dim oSheet
For Each oSheet In ThisWorkbook.Sheets
If oSheet.Name = sSheetName Then
IsSheetExists = True
Exit Function
End If
Next
IsSheetExists = False
End Function
Sub AddContainer(sName)
With ThisWorkbook.Sheets("storage").OLEObjects.Add(ClassType:="Forms.Label.1")
.Visible = False
.Name = sName
End With
End Sub
Sub RemoveContainer(sName)
ThisWorkbook.Sheets("storage").OLEObjects.Item(sName).Delete
End Sub
Sub PutContent(sName, sContent)
ThisWorkbook.Sheets("storage").OLEObjects.Item(sName).Object.Caption = sContent
End Sub
Function GetContent(sName)
GetContent = ThisWorkbook.Sheets("storage").OLEObjects.Item(sName).Object.Caption
End Function
Function ReadTextFile(sPath, iFormat)
With CreateObject("Scripting.FileSystemObject").OpenTextFile(sPath, 1, False, iFormat)
ReadTextFile = ""
If Not .AtEndOfStream Then ReadTextFile = .ReadAll
.Close
End With
End Function

Excel Macro to search if content of a column (filename) exists in a folder

I have an excel sheet where I have the names of jpegs in columns F & G from rows 2 to 1800. I would like to use a macro in order to see if these Jpegs exist in a folder on my computer (mac) at a certain directory (ex. /user/Dropbox/Content/productinfo/pictures). If they do exist i would like to return the value "exists", if not, then "doesnt". The only issue is in a few cases no Jpeg exists in the spreadsheet so there is nothing to look up
I'm new to excel Macros. Please help me out!
Thanks in advance!
You can use a user-defined function for that. In you case, you can call the below using:
=fileexists("C:\MyPath\"&f2)
Here's the function
Public Function FileExists(sPath As String)
If lcase(right(sPath,5)) <> ".jpeg" Then
FileExists = ""
Else
If Len(Dir(sPath)) > 0 Then
FileExists = "Exists"
Else
FileExists = ""
End If
End If
End Function
Dim iCount As Integer
iCount = Application.WorksheetFunction.COUNTIF(Range("F2:G1800"),".jpg")
if iCount > 0 Then
'Do your checks
End If

VBA duplicate PDF file

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