The file path doesn't work when:
Path = Sheets("Sheet1").Range("C2").Value & "\"
The file path in C2 doesn't include \ at the end
Sub Make_Folders_And_SubFolders()
Dim GPath, GName, UName, UGroup As String
Dim UserID, Groups, G, U As Range
Dim Gcounter, Ucounter As Integer
GPath = Sheets("Sheet1").Range("C2").Value & "\"
On Error GoTo Finish
If Len(GPath) = 0 Or Right(GPath, 1) <> "\" Then
Finish:
MsgBox "Please, check if:" & vbNewLine _
& "1- Folder Path is empty." & vbNewLine _
& "2- or "" \ "" is missing at the end of the path." & vbNewLine _
& "3- or Path does not exist.", vbCritical
Exit Sub
End If
Set Groups = Sheets("Sheet1").Range(Cells(5, "P"), Cells(Rows.Count, "P").End(xlUp))
Set UserID = Sheets("Sheet1").Range(Cells(5, "Q"), Cells(Rows.Count, "Q").End(xlUp))
For Each G In Groups
GName = Trim(G.Value) & "_Group"
If Len(Dir(GPath & GName, vbDirectory)) > 0 Then
GoTo Nxt1
Else
MkDir GPath & GName
Gcounter = Gcounter + 1
End If
Nxt1:
Next G
For Each U In UserID
UName = Trim(U.Value)
UGroup = Trim(U.Offset(0, 1).Value) & "_Group"
If Len(Dir(GPath & UGroup & "\" & UName, vbDirectory)) > 0 Then
GoTo Nxt2
Else
MkDir GPath & UGroup & "\" & UName
Ucounter = Ucounter + 1
End If
Nxt2:
Next U
If Gcounter + Ucounter = 0 Then
MsgBox "All Folders exist, " & vbNewLine & "No folder to be created"
Else
MsgBox "Job Done !!" & vbNewLine _
& "Group Folders created: = " & Gcounter & vbNewLine _
& "User ID Folders created: = " & Ucounter, _
Title:="Foders Created Count"
End If
End Sub
May I suggest for file operations and path building use a FileSystemObject. It absolutely negates the need to have \ on the end of paths, as it is smart enough to add it when needed. Specifically, the fso.BuildPath() method was designed to suit this exact need.
Public Sub CombinePathTest()
Dim path As String, fn As String
path = fso.GetParentFolderName(Sheets("Sheet1").Range("C2").Value)
fn = fso.BuildPath(path, Uname)
End Sub
From the documentation, you can see there are a lot of helpful functions that take the stress out of building paths, opening files, creating or deleting, or check for existence.
and by defining as a reference, and adding a global fso object you have access to Intellisense while writing code
Try the following. Note that I haven't touched anything from For Each G In Groups to the end.
Sub FileOperation()
Dim GPath As String, GName As String, UName As String, UGroup As String
Dim UserID As Range, Groups As Range, G As Range, U As Range
Dim Gcounter As Long, Ucounter As Long
Dim pSep As String: pSep = Application.PathSeparator
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = wb.Worksheets("Sheet1")
GPath = ws.Range("C2").Value
If Len(GPath) = 0 Then
MsgBox "Path is empty.", vbCritical
Exit Sub
End If
If Right(GPath, 1) <> pSep Then
GPath = GPath & pSep
End If
Set Groups = ws.Range(ws.Cells(5, "P"), ws.Cells(Rows.Count, "P").End(xlUp))
Set UserID = ws.Range(ws.Cells(5, "Q"), ws.Cells(Rows.Count, "Q").End(xlUp))
For Each G In Groups
GName = Trim(G.Value) & "_Group"
If Len(Dir(GPath & GName, vbDirectory)) > 0 Then
GoTo Nxt1
Else
MkDir GPath & GName
Gcounter = Gcounter + 1
End If
Nxt1:
Next G
For Each U In UserID
UName = Trim(U.Value)
UGroup = Trim(U.Offset(0, 1).Value) & "_Group"
If Len(Dir(GPath & UGroup & "\" & UName, vbDirectory)) > 0 Then
GoTo Nxt2
Else
MkDir GPath & UGroup & "\" & UName
Ucounter = Ucounter + 1
End If
Nxt2:
Next U
If Gcounter + Ucounter = 0 Then
MsgBox "All Folders exist, " & vbNewLine & "No folder to be created"
Else
MsgBox "Job Done !!" & vbNewLine _
& "Group Folders created: = " & Gcounter & vbNewLine _
& "User ID Folders created: = " & Ucounter, _
Title:="Foders Created Count"
End If
End Sub
Related
Need to split the 3rd row and have it in the below xml format.
My Excel data:
ID
EMail
UserGroupID
Aravind
Aravind#gmail.com
Sports(12-34)
Aravind2
Aravind2#gmail.com
Sports(3-24-5),Health(5-675-85), Education(57-85-96)
My XML data:
<?xml version="1.0" encoding="utf-8"?>
<Core-data ContextID="Context1" WorkspaceID="Main">
<UserList>
<User ID="Aravind" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com">
<Name>Aravind</Name>
<UserGroupLink UserGroupID="12-34"/>
</User>
<User ID="Aravind2" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com">
<Name>Aravind2</Name>
<UserGroupLink UserGroupID="3-24-5"/>
<UserGroupLink UserGroupID="5-675-85"/>
<UserGroupLink UserGroupID="57-85-96"/>
</User>
</UserList>
</Core-data>
The code Im using:(Need change in delimiting the 3 rd row & location only)
Sub Generate_xml()
Const FOLDER = "C:\Temp\"
Const XLS_FILE = "UserDataEntry.xlsm"
Const XML_FILE = "User XML.xml"
Const XML = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCrLf & _
"<Core-data ContextID=""Context1"" WorkspaceID=""Main"">" & vbCrLf & _
" <UserList>" & vbCrLf
Dim wb As Workbook, ws As Worksheet, ar, s As String
Dim iLastRow As Long, r As Long, n As Integer
' open source workbook
Set wb = Workbooks.Open(FOLDER & XLS_FILE, 1, 1)
Set ws = wb.Sheets("Sheet1")
iLastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
' create XML document
'<User ID="Aravind" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com.com">
' <Name>Aravind</Name>
' <UserGroupLink UserGroupID="Sports"/>
'</User>
s = XML
For r = 2 To iLastRow
s = s & " <User ID=""" & ws.Cells(r, 1) & """" & _
" ForceAuthentication=""false"" Password=""1234""" & _
" EMail=""" & ws.Cells(r, 2) & """>" & vbCrLf
s = s & " <Name>" & ws.Cells(r, 1) & "</Name>" & vbCrLf
ar = Split(ws.Cells(r, 3), ",")
For n = LBound(ar) To UBound(ar)
s = s & " <UserGroupLink UserGroupID=""" & Trim(ar(n)) & """/>" & vbCrLf
Next
s = s & " </User>" & vbCrLf
Next
s = s & " </UserList>" & vbCrLf & "</Core-data>"
' save
Dim fso, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.createtextfile(FOLDER & XML_FILE)
ts.write s
ts.Close
MsgBox "Xml created to " & FOLDER & XML_FILE
End Sub
Is there is any way to run this VBA code in any location and the XML generated to be in same location.
Kindly share your inputs & thanks in advance.
Try something like this:
Sub Generate_xml()
Const FOLDER = "C:\Temp\"
Const XLS_FILE = "UserDataEntry.xlsm"
Const XML_FILE = "User XML.xml"
Const XML = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCrLf & _
"<Core-data ContextID=""Context1"" WorkspaceID=""Main"">" & vbCrLf & _
" <UserList>" & vbCrLf
Dim wb As Workbook, ws As Worksheet, s As String, savePath As String
Dim r As Long, e
' open source workbook
Set wb = Workbooks.Open(FOLDER & XLS_FILE, 1, 1)
Set ws = wb.Sheets("Sheet1")
' create XML document
s = XML
For r = 2 To ws.Cells(Rows.Count, "A").End(xlUp).Row
s = s & " <User ID=""" & ws.Cells(r, 1) & """" & _
" ForceAuthentication=""false"" Password=""1234""" & _
" EMail=""" & ws.Cells(r, 2) & """>" & vbCrLf
s = s & " <Name>" & ws.Cells(r, 1) & "</Name>" & vbCrLf
For Each e In TextInParentheses(ws.Cells(r, 3).Value)
s = s & " <UserGroupLink UserGroupID=""" & Trim(e) & """/>" & vbCrLf
Next e
s = s & " </User>" & vbCrLf
Next
s = s & " </UserList>" & vbCrLf & "</Core-data>"
'wb.Close false 'close source workbook
' save to same path as running code
savePath = ThisWorkbook.Path & "\" & XML_FILE
PutContent savePath, s
MsgBox "Xml created at '" & savePath & "'", vbInformation
End Sub
'all texts enclosed in parentheses as a collection
Function TextInParentheses(txt As String)
Dim re As Object
Dim allMatches, m, col As New Collection
Set re = CreateObject("VBScript.RegExp")
re.Pattern = "\(([^\)]+)\)"
re.ignorecase = True
re.Global = True
Set allMatches = re.Execute(txt)
For Each m In allMatches
col.Add Trim(m.submatches(0))
Next m
Set TextInParentheses = col
End Function
'Save text `content` to a text file at `f`
Sub PutContent(f As String, content As String)
CreateObject("scripting.filesystemobject"). _
opentextfile(f, 2, True).write content
End Sub
My code renames folders based on what is in first column:
Dim sFolder As String
Option Explicit
Sub addPrefix()
Dim strfile As String
Dim filenum As String
Dim strOldDirName
Dim strNewDirName
strfile = Dir(sFolder)
Dim old_name, new_name As String
Dim i As Long
With ThisWorkbook.Worksheets("data")
For i = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
strOldDirName = sFolder & ThisWorkbook.Worksheets("data").Cells(i, 2).Value
strNewDirName = sFolder & ThisWorkbook.Worksheets("data").Cells(i, 1).Value & " " & ThisWorkbook.Worksheets("data").Cells(i, 2).Value
Name strOldDirName As strNewDirName
Next i
End With
End Sub
and then I check for duplicates on Column C (email column). If they are a duplicate I move them to their 'master' folder (which is just the first of the duplicates found). Upon this, it adds the suffix ' - MASTER' on to the folder.
Here is the code to move duplicates:
Sub moveDuplicates()
' This will find duplicates and move them into a master folder. It'll will then delete the row
Dim masterID
Dim masterPlatform
Dim objFileSystem
Dim FromPath As String
Dim ToPath As String
Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Dim masterOldFolderName
Dim masterNewFolderName
Dim masterSuffix
Dim LastRow As Long, i As Long
Dim rngWhole As Range, rngSplit As Range
masterID = 0
masterPlatform = 0
masterSuffix = " - MASTER"
masterOldFolderName = ""
masterNewFolderName = ""
With ThisWorkbook.Worksheets("data")
LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
Set rngWhole = .Range("C1:C" & LastRow)
.Range("E" & 1).Value = rngWhole
For i = 1 To LastRow
If WorksheetFunction.CountIf(rngWhole, .Range("C" & i).Value) > 1 Then
Set rngSplit = .Range("C1:C" & i)
If WorksheetFunction.CountIf(rngSplit, .Range("C" & i).Value) = 1 Then
masterID = .Range("B" & i).Value
masterPlatform = .Range("A" & i).Value
'' Renme master folders with subfix of "- MASTER"
masterOldFolderName = sFolder & masterPlatform & " " & masterID
masterNewFolderName = sFolder & masterPlatform & " " & masterID & masterSuffix
Name masterOldFolderName As masterNewFolderName
'' End of renaming
'.Range("D" & i).Value = "MASTER " & masterID
Else
'.Range("D" & i).Value = "CHILD " & masterID & " This folder: " & .Range("B" & i).Value
'MOVING FOLDER
FromPath = sFolder & .Range("A" & i).Value & " " & .Range("B" & i).Value '<< Change
ToPath = sFolder & masterPlatform & " " & masterID & masterSuffix & "\" '<< needs the slash to go into the folder
.Range("H" & i).Value = "From: " & FromPath
.Range("I" & i).Value = "From: " & ToPath
'Check if source and target folder exists
If objFileSystem.FolderExists(FromPath) = True And objFileSystem.FolderExists(ToPath) = True Then
objFileSystem.MoveFolder Source:=FromPath, Destination:=ToPath
lblStatus.Caption = "Moving " & FromPath & " To " & ToPath
Rows(i).EntireRow.Delete
lblStatus.Caption = " Deleting " & .Range("A" & i).Value & " " & .Range("B" & i).Value
'MsgBox "Source folder has moved to target folder"
Else
'MsgBox "Either source or target folder does not exist"
End If
' END OF MOVING FOLDER
' ROW GETS DELETED
End If
'.Range("C" & i).Interior.ColorIndex = 3
End If
Next i
End With
End Sub
My script works to a certain degree:
But it just puts everything into the first 'MASTER' folder
Here is my sheet:
I then call this from a button:
' Open the select folder prompt
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = -1 Then ' if OK is pressed
sFolder = .SelectedItems(1) & "\"
End If
End With
If sFolder <> "" Then ' if a file was chosen
Me.txtFolderPath.Text = sFolder
'' calls functions
addPrefix
moveDuplicates
Sheet_SaveAs ' saves output
end sub
Is the reason it is not performing as expected due to I am calling it wrongly?
Full code: https://www.dropbox.com/s/k06b5hydc4v7bpn/so-files.zip?dl=0
(code can be run from developer> forms> userform1)
DEBUGGING:
I think the problem seems to arise here when debugging:
'' Renme master folders with subfix of "- MASTER"
masterOldFolderName = sFolder & masterPlatform & " " & masterID
masterNewFolderName = sFolder & masterPlatform & " " & masterID & masterSuffix
Name masterOldFolderName As masterNewFolderName
'' End of renaming
I am not sure if this is because it is in the wrong place (which I assume)
i have a folder with over 100 workbooks (all with the same structure) with only one sheet in it . I need a macro to open the workbook and check a hole row(9th row) if a value exist in the cells (30 columns). if this value exist , need to check the value to the below cell (10th row). if criteria met the workbook closes , else remains open for corrections
I'm new to vba so help need
my code doesn't work
Sub scannerblaine()
Dim SPath As String 'path to check
Dim sFname As String 'the name of the workbooks for scaning (if all scaned = * )
Dim wBk As Workbook
Dim wSht As Variant 'the name of the sheets to be scaned
Dim r1, r2 As Integer 'this is the rows for scanning
Dim c1 As Integer 'columns for scanning
Dim blaine, varblaine, b1, b2 As Double
Dim res As Integer
res = MsgBox(" SCANNING OF MT FOLDER" & vbCrLf & vbCrLf _
& "CHOOSE FOLDER" & vbCrLf & vbCrLf _
& "NAME OF THE EXCEL FILES" & vbCrLf & vbCrLf _
& "IF ALL THE SAME PLACE {*} " & vbCrLf & vbCrLf _
& "", vbOKCancel + vbDefaultButton2, " INFO !!!")
If res = vbCancel Then
Exit Sub
End If
Application.EnableEvents = False
Application.ScreenUpdating = False
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder for scanning"
.Show
.AllowMultiSelect = False
If .SelectedItems.count = 0 Then 'if no folder is selected , abort
MsgBox "You did not select a folder"
Exit Sub
End If
SPath = .SelectedItems(1) & "\" 'assign selected folder to be the scanned folder
End With
ChDir SPath
sFname = InputBox("Enter a filename pattern")
sFname = Dir(SPath & "\" & sFname & ".xl*", vbNormal)
' INPUT BOX FOR blaine ###################################################################################################
blaine = Application.InputBox("TARGET BLAINE", Type:=1)
varblaine = Application.InputBox("BLAINE VARIATION", Type:=1)
b1 = blaine - varblaine
b2 = blaine + varblaine
Dim resl As Integer
resl = MsgBox(b1 & " to " & b2, vbOKCancel + vbDefaultButton2)
If resl = vbCancel Then
Exit Sub
End If
ChDir SPath
Filename = Dir(SPath & "\" & "*.xl*")
Do While Filename <> ""
Workbooks.Open Filename:=SPath & Filename, ReadOnly:=True
Set wBk = Workbooks.Open(Filename)
For c1 = 6 To 36 '0 '########################################################################################
r1 = 9
If Cells(r1, c1) = "I52,5N" Then
If Cells(r1 + 1, c1) < b2 And Cells(r1 + 1, c1) > b1 Then
wBk.Close
End If
End If
Next c1
Application.DisplayAlerts = False
Filename = Dir()
Loop
MsgBox _
"SCAN IN FOLDER" & vbCrLf & vbCrLf _
& SPath & vbCrLf & vbCrLf _
& " COMPLETE"
End Sub
Sub scannerblaine()
Dim SPath As String 'path to check
Dim sFname As String 'the name of the workbooks for scaning (if all scaned = * )
Dim wBk As Object
Dim wSht As Variant 'the name of the sheets to be scaned
Dim r1, r2 As Integer 'this is the rows for scanning
Dim c1, c2 As Variant 'columns for scanning
Dim blaine, varblaine, b1, b2 As Integer
Dim res As Integer
res = MsgBox(" ΘΑ ΣΑΡΩΘΕΙ ΕΝΑΣ ΦΑΚΕΛΟΣ ΤΟΥ ΑΡΧΕΙΟΥ MT" & vbCrLf & vbCrLf _
& "ΕΠΕΛΕΞΕ ΠΟΙΟΣ ΑΠΟ ΤΟ ΠΑΡΑΘΥΡΟ ΔΙΑΛΟΓΟΥ" & vbCrLf & vbCrLf _
& "ΚΑΤΟΠΙΝ ΘΑ ΣΟΥ ΖΗΤΗΘΕΙ ΤΟ ΟΝΟΜΑ ΤΩΝ EXCEL ΑΡΧΕΙΩΝ" & vbCrLf & vbCrLf _
& "ΕΠΕΙΔΗ ΕΙΝΑΙ ΤΑ ΙΔΙΑ ΑΠΛΑ ΒΑΛΕ [ * ] [αστερισκος] " & vbCrLf & vbCrLf _
& "", vbOKCancel + vbDefaultButton2, " ΕΝΗΜΕΡΩΣΗ !!!")
If res = vbCancel Then
Exit Sub
End If
Application.EnableEvents = False
Application.ScreenUpdating = False
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder for scanning"
.Show
.AllowMultiSelect = False
If .SelectedItems.count = 0 Then 'if no folder is selected , abort
MsgBox "You did not select a folder"
Exit Sub
End If
SPath = .SelectedItems(1) & "\" 'assign selected folder to be the scanned folder
End With
ChDir SPath
sFname = InputBox("Enter a filename pattern")
sFname = Dir(SPath & "\" & sFname & ".xl*", vbNormal)
'Να φτιαξω input box για την ποιοτητα I42,5R ή I52,5N και να συμπεριλαβω την ποιοτητα στο input box του blaine παρακατω
' INPUT BOX FOR blaine ###################################################################################################
blaine = Application.InputBox("ΔΩΣΕ ΣΤΟΧΟ BLAINE", Type:=1)
varblaine = Application.InputBox("ΔΩΣΕ ΕΥΡΟΣ ΔΙΑΚΥΚΑΝΣHΣ BLAINE", Type:=1)
b1 = blaine - varblaine
b2 = blaine + varblaine
Dim resl As Integer
resl = MsgBox("ΟΡΙΑ BLAINE ΑΠΟ " & b1 & " ΕΩΣ " & b2, vbOKCancel + vbDefaultButton2)
If resl = vbCancel Then
Exit Sub
End If
ChDir SPath
Filename = Dir(SPath & "\" & "*.xl*")
Do While Filename <> ""
Workbooks.Open Filename:=SPath & Filename, ReadOnly:=True
Set wBk = Workbooks.Open(Filename)
'CHECK FOR BLAINE VALUES IN CELLS ##########################################################################################
For c1 = 6 To 30
r1 = 9
If Cells(r1, c1) = "I52,5N" Then
If Cells(r1 + 2, c1) > b2 Or Cells(r1 + 2, c1) < b1 Then GoTo c
End If
Next c1
wBk.Close
c:
Filename = Dir()
Loop
MsgBox _
"Η ΣΑΡΩΣΗ ΣΤΟΝ ΦΑΚΕΛΟ" & vbCrLf & vbCrLf _
& SPath & vbCrLf & vbCrLf _
& "ΟΛΟΚΛΗΡΩΘΗΚΕ" & vbCrLf & vbCrLf _
& "ΤΑ ΑΡΧΕΙΑ ΜΕ ΣΦΑΛΜΑΤΑ" & vbCrLf & vbCrLf _
& "ΠΑΡΑΜΕΝΟΥΝ ΑΝΟΙΧΤΑ ΓΙΑ ΕΠΕΞΕΡΓΑΣΙΑ"
End Sub
I am trying to use a match function to reference a cell which contains the new file name.
Sub SaveAs()
Dim FName As String
Dim FPath As String
Dim NewBook As Workbook
FPath = "\\G:\Exceptions"
FName = (Application.Match("Test", Worksheets("Sheet 1").Range("A1:A42"), 0, 2)) & ".xls"
If Dir(FPath & "\" & FName) <> "" Then
MsgBox "File " & FPath & "\" & FName & " already exists"
Else
ThisWorkbook.SaveAs filename:=FPath & "\" & FName
End If
End Sub
Can this be done or am I better to find another way to do this?
Following on Scott's answer:
A first Error is with your Match.
Application.Match("Test", Worksheets("Sheet 1").Range("A1:A42"), 0, 2))
needs to become
Application.Worksheetfunction.Match("Test", Worksheets("Sheet 1").Range("A1:A42"), 0)
Also Match returns only a long so you need to add Cells() to find the name you need
Cells(Application.Worksheetfunction.Match("Test", Worksheets("Sheet 1").Range("A1:A42"), 0),2).value
gives you the name you need
Now if you add the case where the match is not found you end up with this code:
Sub SaveAs()
Dim FName As String
Dim FPath As String
Dim NewBook As Workbook
Dim Mtch As Long
FPath = "\\G:\Exceptions"
Mtch = Application.WorksheetFunction.Match("Test", Worksheets("Sheet 1").Range("A1:A42"), 0)
FName = Cells(Application.WorksheetFunction.Match("Test", Worksheets("Sheet 1").Range("A1:A42"), 0), 2) & ".xls"
MsgBox FName
If Not IsError(Mtch) Then
If Dir(FPath & "\" & Worksheets("Sheet 1").Cells(Mtch, 1).Value) <> "" Then
MsgBox "File " & FPath & "\" & FName & " already exists"
Else
ThisWorkbook.SaveAs Filename:=FPath & "\" & FName
End If
Else
MsgBox "the value not found in the column"
End If
End Sub
Alternatively you can also find the Row like this:
Mtch = Findval("TEST", Range("A1:A42"))
MsgBox Mtch
FName = Cells(Application.WorksheetFunction.Match("Test", Worksheets("Sheet 1").Range("A1:A42"), 0), 2) & ".xls"
MsgBox FName
If Not IsError(Mtch) Then
If Dir(FPath & "\" & Worksheets("Sheet 1").Cells(Mtch, 1).Value) <> "" Then
MsgBox "File " & FPath & "\" & FName & " already exists"
Else
ThisWorkbook.SaveAs Filename:=FPath & "\" & FName
End If
Else
MsgBox "the value not found in the column"
End If
End Sub
Function Findval(VALUESEARCHED As String, ra As Range) As Variant
Dim A As Range
Set A = ra.Find(What:=VALUESEARCHED, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
Findval = A.Row
End Function
Match returns a Long, the relative location in the 1 dimensional range. You will need to use that number with something else, like Cells() to return the actual name.
Sub SaveAs()
Dim Mtch as Long
Dim FPath As String
Dim NewBook As Workbook
FPath = "\\G:\Exceptions"
Mtch = (Application.Match("Test", Worksheets("Sheet 1").Range("A1:A42"), 0)) & ".xls"
If Dir(FPath & "\" & Worksheets("Sheet 1").Cells(Mtch,2).Value) <> "" Then
MsgBox "File " & FPath & "\" & FName & " already exists"
Else
ThisWorkbook.SaveAs filename:=FPath & "\" & FName
End If
End Sub
Now another thing. You will want to deal with the error if a match is not found:
Sub SaveAs()
Dim Mtch as Variant
Dim FPath As String
Dim NewBook As Workbook
FPath = "\\G:\Exceptions"
Mtch = (Application.Match("Test", Worksheets("Sheet 1").Range("A1:A42"), 0)) & ".xls"
If not iserror(mtch) then
If Dir(FPath & "\" & Worksheets("Sheet 1").Cells(Mtch,2).Value) <> "" Then
MsgBox "File " & FPath & "\" & FName & " already exists"
Else
ThisWorkbook.SaveAs filename:=FPath & "\" & FName
End If
Else
msgbox "the value not found in the column
End if
End Sub
I have used hyperlinks.add several times now and never had any problems with it.
Now I added a line of code: SourceBook.Sheets(ESN & "_SV" & SV).Hyperlinks.Add Anchor:=Range("A" & i), _
Address:=ToPath & NewName to my base code (which you can find under here). This should add a link to the newly created document.
The problem is that excel always says it cannot open the file. The link I enter via code is right, as I copied it with debug.print and it opened the file without a problem.
It came to my attention that the hyperlink I added was modified by excel when I hold my mouse over the hyperlink. I wonder how this is possible.
A second problem I encounterd is that when I enter the hyperlink manually and navigate manually to the file to make sure it takes the right file, excel still modifies my link and says "cannot open specified file".
Anyone an idea what might go wrong here? Thanks!
Code:
`Application.ScreenUpdating = False
Dim i, j, FSO As Object, SV, ESN, PartName, ToPath, FromPath, NewName, MsgBoxAnswer, TargetBook As Workbook, SourceBook As Workbook
Dim OS, PN, SN, ProjectNumber, Customer, StartDate, EndDate, LastRowCMM
ESN = ActiveWorkbook.ActiveSheet.Range("G2").Value
SV = ActiveWorkbook.ActiveSheet.Range("K2").Value
ProjectNumber = ActiveWorkbook.ActiveSheet.Range("A3").Value
Customer = ActiveWorkbook.ActiveSheet.Range("G3").Value
Set FSO = CreateObject("scripting.filesystemobject")
PGB.Min = 0
PGB.Value = 0
PGB.Max = 22
'Create main folder
If SV <> 1 Then
SV = "(SV " & SV & ")"
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & " " & SV
Else
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN
End If
If FSO.folderexists(ToPath) = True Then
MsgBoxAnswer = MsgBox("Folder already created.", vbExclamation, "Folder exists.")
Exit Sub
End If
FSO.createfolder (ToPath)
'Create all Excel files & fill them in
For i = 6 To 27
FromPath = "U:\tmo\VANMOLLE\Fiches constat\Template fiches constat LEAP.xlsm"
If SV <> 1 Then
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & " " & SV & "\"
Else
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & "\"
End If
FSO.copyfile Source:=FromPath, Destination:=ToPath
NewName = "#" & ESN & "_" & ActiveWorkbook.ActiveSheet.Range("A" & i) & ".xlsm"
If SV <> 1 Then
FromPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & " " & SV & "\Template fiches constat LEAP.xlsm"
Else
FromPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & "\Template fiches constat LEAP.xlsm"
End If
Name FromPath As ToPath & NewName
Set SourceBook = ThisWorkbook
Set TargetBook = Workbooks.Open(ToPath & NewName)
TargetBook.Sheets("Sheet1").Activate
PartName = SourceBook.ActiveSheet.Range("A" & i).Value
OS = SourceBook.ActiveSheet.Range("D" & i).Value
PN = SourceBook.ActiveSheet.Range("B" & i).Value
SN = SourceBook.ActiveSheet.Range("C" & i).Value
If SN = "" Then SN = "N/A"
StartDate = SourceBook.ActiveSheet.Range("G" & i).Value
EndDate = SourceBook.ActiveSheet.Range("H" & i).Value
'check for right CMM
'LastRowCMM = TargetBook.Sheets("Révision CMM").Range("B6").End(xlDown).Row
'For j = 1 To LastRowCMM
'If PartName = TargetBook.Sheets("Révision CMM").Range("A" & j).Value Then ActiveWorkbook.ActiveSheet.Range("A23").Value = ActiveWorkbook.Sheets("Révision CMM").Range("B" & j).Value
'Next j
TargetBook.ActiveSheet.Range("B9").Value = PartName
TargetBook.ActiveSheet.Range("B10").Value = OS
TargetBook.ActiveSheet.Range("B11").Value = "# " & ESN
TargetBook.ActiveSheet.Range("B12").Value = PN
TargetBook.ActiveSheet.Range("B13").Value = SN
TargetBook.ActiveSheet.Range("E9").Value = StartDate
TargetBook.ActiveSheet.Range("E10").Value = EndDate
TargetBook.ActiveSheet.Range("B14").Value = ProjectNumber
TargetBook.ActiveSheet.Range("B15").Value = Customer
TargetBook.ActiveSheet.PageSetup.PrintArea = "$A$1:$E$39"
TargetBook.Close True
'Add hyperlink
SourceBook.Sheets(ESN & "_SV" & SV).Hyperlinks.Add Anchor:=Range("A" & i), _
Address:=ToPath & NewName
Application.Wait (Now + TimeValue("00:00:01"))
Progress.PGB.Value = i - 5
Progress.Lbl.Caption = "File " & i - 5 & " of 22 copied."
Next i
Application.ScreenUpdating = True`
First thing first - declare each variable explicitly. E.g.:
Dim i as Long, j as Long, FSO As Object, SV as String, ESN as String and etc.
The way in your code - Dim i, j, SV, ESN, PartName, ToPath they are declared as variant.
Second thing second - try something really very small to debug further. E.g. write this small piece:
Sub TestMe()
With Worksheets(1)
.Hyperlinks.Add anchor:=.Range("A1"), Address:="C:\Users\UserName\Desktop\test.docx"
End With
End Sub
and check whether it works. If it doesn't, debug further, check whether cells are locked or anything similar.