Hello everyone yesterday ı try to do Save Excel Row Via Vba Loop, now my problem is give hyplinks that file via macro.
I try to explain in photo and my codes are below
Sub Hyperlinks()
Dim wks As Worksheet
Dim hl As Hyperlink
Const RootPath As String = "X:\EVEREST-2\EVEREST ERP\ÜRETİM\PDM SOLID DOSYA YOLU\"
Const SeriCol As Long = 3
Const NameCol As Long = 4
Const YearCol As Long = 24
Set wks = ActiveSheet
Dim r As Long: r = FirstRow
Dim FileBaseName As String: FileBaseName = ws.Cells(r, SeriCol)
Dim hl_name As String: hl_name = ws.Cells(r, NameCol)
Dim year As String: year = ws.Cells(r, YearCol)
Do Until Len(hl_name) = 0
wks.Hyperlinks.Add ws.Cells(r, NameCol), Address:=(RootPath & year & "\" & FileBaseName & ".bat"TextToDisplay:=hl_name)
r = r + 1
Loop
MsgBox "Hyperlinks created.", vbInformation End sub
Create Hyperlinks
' *** You want to reference the model cell before and at the end of the loop.
A Quick Fix
Option Explicit
Sub CreateHyperlinks()
Const RootPath As String = "X:\EVEREST-2\EVEREST ERP\ÜRETIM\PDM SOLID DOSYA YOLU\"
Const YearCol As String = "X"
Const SerialCol As String = "C"
Const ModelCol As String = "D"
Const FirstRow As Long = 2
Dim wks As Worksheet: Set wks = ActiveSheet ' improve!
Dim r As Long: r = FirstRow
Dim ModelCell As Range: Set ModelCell = wks.Cells(r, ModelCol) ' ***
Dim FilePath As String
Dim YearPath As String
Dim Serial As String
Do Until Len(CStr(ModelCell.Value)) = 0
YearPath = CStr(wks.Cells(r, YearCol)) & "\"
Serial = CStr(wks.Cells(r, SerialCol))
FilePath = RootPath & YearPath & Serial & ".bat"
wks.Hyperlinks.Add Anchor:=ModelCell, Address:=FilePath
r = r + 1
Set ModelCell = wks.Cells(r, ModelCol) ' ***
Loop
MsgBox "Hyperlinks created.", vbInformation
End Sub
There is a comma missing between ".bat" and TextToDisplay:
Address:=(RootPath & year & "\" & FileBaseName & ".bat"TextToDisplay:=hl_name)
Note: There is no need to use the TextToDisplay parameter when the display text is the same as the anchor cell value.
Refactored Code
Sub Hyperlinks()
Dim wks As Worksheet
Dim hl As Hyperlink
Const RootPath As String = "X:\EVEREST-2\EVEREST ERP\ÜRETIM\PDM SOLID DOSYA YOLU\"
Const SeriCol As Long = 3
Const NameCol As Long = 4
Const YearCol As Long = 24
Set wks = ActiveSheet
Dim r As Long: r = FirstRow
Dim FileBaseName As String: FileBaseName = ws.Cells(r, SeriCol)
Dim year As String: year = ws.Cells(r, YearCol)
Dim Address As String
Do Until Len(hl_name) = 0
Address = RootPath & year & "\" & FileBaseName & ".bat"
wks.Hyperlinks.Add ws.Cells(r, NameCol), Address:=Address
r = r + 1
Loop
MsgBox "Hyperlinks Added"
End Sub
ı fix it now it works
Sub Hyperlinks1()
Dim hl As Hyperlink
Const RootPath As String = "X:\EVEREST-2\EVEREST ERP\ÜRETİM\PDM SOLID DOSYA YOLU\"
Const SeriCol As Long = 3
Const NameCol As Long = 4
Const YearCol As Long = 24
Dim ws As Worksheet: Set ws = ActiveSheet
Dim r As Long: r = 4
Dim FileBaseName As String: FileBaseName = ws.Cells(r, SeriCol)
Dim hl_name As String: hl_name = ws.Cells(r, NameCol)
Dim year As String: year = ws.Cells(r, YearCol)
year = Right(year, 4)
Do Until Len(hl_name) = 0
With ws
.Hyperlinks.Add Anchor:=.Cells(r, NameCol), _
Address:=RootPath & year & "\" & FileBaseName & ".bat", _
ScreenTip:="Click to open 3D Solid File", _
TextToDisplay:=hl_name
End With
r = r + 1
FileBaseName = ws.Cells(r, SeriCol)
hl_name = ws.Cells(r, NameCol)
year = ws.Cells(r, YearCol)
year = Right(year, 4)
Loop
MsgBox "Hyperlinks created.", vbInformation
End Sub
Related
I'm trying to name sheets based on the current date. I need a counter variable to name sheets so they're unique.
I made two attempts:
Sub COPIAR_MODELO()
Application.ScreenUpdating = False
Dim i As Integer, x As Integer
Dim shtname As String
Dim WSDummy As Worksheet
Dim TxtError As String
Dim counter As Long
counter = 0
Name01:
For counter = 1 To 100 Step 0
TxtError = ""
counter = counter + 1
shtname = Format(Now(), "dd mm yyyy") & " - " & counter
On Error Resume Next
Set WSDummy = Sheets(shtname)
If Not (WSDummy Is Nothing) Then TxtError = "Name taken, additional sheet added!"
Next counter
If TxtError <> "" Then MsgBox "" & TxtError: GoTo Name01
Sheets("MODELO - NFS").Copy Before:=Sheets("MODELO - DEMAIS"): ActiveSheet.Name = shtname
Application.ScreenUpdating = True
End Sub
Expected result:
And:
Sub COPIAR_MODELO()
Application.ScreenUpdating = False
Dim i As Integer, x As Integer
Dim shtname As String
Dim WSDummy As Worksheet
Dim TxtError As String
Dim counter As Long
TxtError = ""
shtname = Format(Now(), "dd mm yyyy")
On Error Resume Next
Set WSDummy = Sheets(shtname)
If Not (WSDummy Is Nothing) Then TxtError = "Name taken, additional sheet added!"
If TxtError <> "" Then MsgBox "" & TxtError: GoTo Name01
If TxtError = "" Then GoTo NameOK
Name01:
For counter = 1 To 100 Step 1
counter = counter + 1
shtname = Format(Now(), "dd mm yyyy") & " - " & counter
Next counter
NameOK:
Sheets("MODELO - NFS").Copy Before:=Sheets("MODELO - DEMAIS"): ActiveSheet.Name = shtname
Application.ScreenUpdating = True
End Sub
Expected result:
I will assign this code to a shape to create the sheets based on the current date.
I prefer result 2.
Copy Template
Sub CopyTemplate()
Const PROC_TITLE As String = "Copy Template"
Const TEMPLATE_WORKSHEET_NAME As String = "MODELO - NFS"
Const BEFORE_WORKSHEET_NAME As String = "MODELO - DEMAIS"
Const DATE_FORMAT As String = "dd mm yyyy"
Const DATE_NUMBER_DELIMITER As String = " - "
Const FIRST_NUMBER As Long = 2
Const FIRST_WORKSHEET_HAS_NUMBER As Boolean = False
Const INPUT_BOX_PROMPT As String = "Input number of worksheets to create."
Const INPUT_BOX_DEFAULT As String = "1"
Dim WorksheetsCount As String: WorksheetsCount _
= InputBox(INPUT_BOX_PROMPT, PROC_TITLE, INPUT_BOX_DEFAULT)
If Len(WorksheetsCount) = 0 Then Exit Sub
Dim DateName As String: DateName = Format(Date, DATE_FORMAT)
Dim NewName As String: NewName = DateName
Dim NewNumber As Long: NewNumber = FIRST_NUMBER
If FIRST_WORKSHEET_HAS_NUMBER Then
NewName = NewName & DATE_NUMBER_DELIMITER & NewNumber
NewNumber = NewNumber + 1
End If
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim wsTemplate As Worksheet
Set wsTemplate = wb.Worksheets(TEMPLATE_WORKSHEET_NAME)
Dim wsBefore As Worksheet
Set wsBefore = wb.Worksheets(BEFORE_WORKSHEET_NAME)
Dim wsNew As Worksheet
Dim WorksheetNumber As Long
Application.ScreenUpdating = False
Do While WorksheetNumber < WorksheetsCount
On Error Resume Next
Set wsNew = wb.Worksheets(NewName)
On Error GoTo 0
If wsNew Is Nothing Then
wsTemplate.Copy Before:=wsBefore
wsBefore.Previous.Name = NewName
WorksheetNumber = WorksheetNumber + 1
Else
NewName = DateName & DATE_NUMBER_DELIMITER & NewNumber
NewNumber = NewNumber + 1
Set wsNew = Nothing
End If
Loop
Application.ScreenUpdating = True
MsgBox WorksheetsCount & " worksheet" & IIf(WorksheetsCount = 1, "", "s") _
& " created.", vbInformation, PROC_TITLE
End Sub
If you overplay it...
Sub DeleteCreatedWorksheets()
Const PROC_TITLE As String = "Delete Created Worksheets"
Const BEFORE_WORKSHEET_NAME As String = "MODELO - DEMAIS"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim wsBefore As Worksheet
Set wsBefore = wb.Worksheets(BEFORE_WORKSHEET_NAME)
Dim wsIndex As Long: wsIndex = wsBefore.Index - 1
If wsIndex > 0 Then
Application.DisplayAlerts = False
Dim n As Long
For n = wsIndex To 1 Step -1
wb.Worksheets(n).Delete
Next n
Application.DisplayAlerts = True
End If
MsgBox wsIndex & " created worksheet" _
& IIf(wsIndex = 1, "", "s") & " deleted.", _
vbInformation, PROC_TITLE
End Sub
the below code is working perfectly but when i added the "'" code the code will stop after n number of loop related for each (rng1) giving an error of overflow run-time error 6
Appreciate if you can help me and if there is any possibility to optimize the code, thank you
the below code is working perfectly but when i added the "'" code the code will stop after n number of loop related for each (rng1) giving an error of overflow run-time error 6
Appreciate if you can help me and if there is any possibility to optimize the code, thank you
Sub Count()
Dim myPath As String
Dim myFile As String
Dim FldrPicker As FileDialog
Dim sh As Worksheet
Dim i As Integer
Dim j As Integer
Dim Count As Integer
Dim CountRecords As String
Dim FilePath As String
Dim UniquePercentage As Integer
Dim SumOfUniqueness As Integer
Dim CountOfUniqueness As Integer
Dim rng As Range
Dim rng1 As Range
Dim LastPosition As Integer
Set sh = ThisWorkbook.Sheets(1)
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Please Select Folder"
.AllowMultiSelect = False
.ButtonName = "Confirm"
If .Show = -1 Then
myPath = .SelectedItems(1) & "\"
Else
End
End If
End With
sh.Cells.ClearContents
myFile = Dir(myPath)
i = 1
Do While myFile <> ""
sh.Cells(1, 1) = "Table Name"
sh.Cells(i + 1, 1) = myFile
sh.Cells(1, 2) = "Count of records"
sh.Cells(1, 3) = "Uniqueness"
Count = Count + 1
myFile = Dir
i = i + 1
Loop
j = 1
For i = 1 To Count
sh.Activate
Worksheets(1).Activate
FilePath = myPath & Range("A" & j + 1).Value
Workbooks.Open FilePath
Worksheets("Properties").Activate
CountRecords = Sheets("Properties").Range("C15").Value
Worksheets("Column Profile").Activate
LastPosition = Range("D10").End(xlDown).Row - 2
For Each rng In Range("D10:D" & LastPosition)
rng.Value = Replace(rng, "-", "0")
rng.Value = CInt(rng)
Next rng
'For Each rng1 In Range("E10:E" & LastPosition)
'rng1.Value = Replace(rng1, "-", "0")
'rng1.Value = CInt(rng1)
'Next rng1
CountOfUniqueness = WorksheetFunction.CountIf(Range("E10:E" & LastPosition), 0)
SumOfUniqueness = WorksheetFunction.Sum(Range("D10:D" & LastPosition))
UniquePercentage = SumOfUniqueness / CountOfUniqueness
ActiveWorkbook.Close (False)
sh.Activate
Worksheets(1).Activate
Range("B" & j + 1).Value = CountRecords
Range("C" & j + 1).Value = UniquePercentage
j = j + 1
Next i
If i = 1 Then
MsgBox("There are no items in this folder:" & Dir(myPath))
End If
End Sub
Hello everyone ı want to save each row of my excel file as a batch file.
I did it for second row but cant do it in loop.
Sub ExportFile()
Dim objFSO, objFile
Dim fileName As String
Dim RootPath As String
Dim text_comm As String
Dim OutputString: OutputString = ""
fileName = Cells([2], [1])
text_comm = Cells([2], [5])
RootPath = "C:\Users\DELL\Desktop\PDM SOLID DOSYA YOLU\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile(RootPath + fileName + ".bat")
Do
OutputString = OutputString & Replace((text_comm), Chr(10), vbNewLine) & vbNewLine
objFile.Write (OutputString)
fileName = Cells([2] + 1, [1]) #Wrong
text_comm = Cells([2] + 1, [5]) #Wrong
Loop Until IsEmpty(text_comm)
Set objFile = Nothing
Set objFSO = Nothing
End Sub
Export Cell Contents As TextFiles
It is assumed that the first column ("A") contains the file base names, and that the fifth column ("E") contains the codes (each code in one cell).
Option Explicit
Sub ExportFiles()
Const RootPath As String = "C:\Users\DELL\Desktop\PDM SOLID DOSYA YOLU\"
Const FirstRow As Long = 2
Const NameCol As Long = 1
Const CodeCol As Long = 5
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
Dim r As Long: r = FirstRow
Dim FileBaseName As String: FileBaseName = ws.Cells(r, NameCol)
Dim text_comm As String: text_comm = ws.Cells(r, CodeCol)
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
Dim fsoFile As Object
Dim OutputString As String
Do Until Len(text_comm) = 0
Set fsoFile = fso.CreateTextFile(RootPath & FileBaseName & ".bat")
OutputString = Replace(text_comm, Chr(10), vbNewLine) & vbNewLine
fsoFile.Write OutputString
r = r + 1
FileBaseName = ws.Cells(r, NameCol)
text_comm = ws.Cells(r, CodeCol)
Loop
MsgBox "Files created.", vbInformation
End Sub
text_comm is merge former cell for each loop
Sub ExportFile()
Dim objFSO, objFile
Dim fileName As String
Dim RootPath As String
Dim text_comm As String
Dim OutputString: OutputString = ""
Dim RowIndex As String
RowIndex = 2
Do
fileName = Cells([RowIndex], [1])
text_comm = Cells([RowIndex], [5])
RootPath = "C:\Users\DELL\Desktop\PDM SOLID DOSYA YOLU\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile(RootPath + fileName + ".bat")
OutputString = OutputString & Replace((text_comm), Chr(10), vbNewLine) & vbNewLine
objFile.Write (OutputString)
RowIndex = RowIndex + 1
Loop Until RowIndex = 6
Set objFile = Nothing
Set objFSO = Nothing
End Sub
Your loop needs to iterate through all rows. Currently it only processes the first row and is stuck there infinitly. You will have to keep record of the current row being processed RowIndex and increment it after each time.
Here is one way to fix your loop:
Dim RowIndex As Integer : RowIndex = 1
Do
OutputString = OutputString & Replace((text_comm), Chr(10), vbNewLine) & vbNewLine
objFile.Write (OutputString)
fileName = Cells([2] + RowIndex, [1])
text_comm = Cells([2] + RowIndex, [5])
RowIndex = RowIndex + 1
Loop Until IsEmpty(text_comm)
I've made a VBA macro that allows me to get information from a specific file from a folder.
The format of the name is Name_Timestamp.extension
I get the TimeStamp.
What I need to do: add the Name file in column G, the time stamp in column B and a word in column J to an Excel with headers.
Do you have any Idea on how I can do it ?
Dim Chemin As String, Fichier As String, timeStamp As String
'Définit le répertoire contenant les fichiers
Chemin = "PATH"
Fichier = Dir(Chemin & "*.*")
timeStamp = Split(Fichier, "_")(2)
timeStamp = Split(timeStamp, ".")(0)
Do While Len(Fichier) > 0
MsgBox (Fichier & "___" & timeStamp)
Fichier = Dir
Loop
End Sub
Split by Timestamp
Adjust the values in the constants section.
The Code
Option Explicit
Sub splitByTimeStamp()
Const wsName As String = "Sheet1"
Const FirstRow As Long = 2
Const FolderPath As String = "C:\Test"
Const aWord As String = "a word"
Const TimeStampDelimiter As String = "_" ' don't use a dot ('.').
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
Dim pSep As String: pSep = Application.PathSeparator
Dim FileName As String: FileName = Dir(FolderPath & pSep & "*.*")
Dim cRow As Long: cRow = FirstRow
Dim sArr() As String
Dim cString As String
Dim NoStamp As String
Dim TimeStamp As String
Dim n As Long
Application.ScreenUpdating = False
Do While Len(FileName) > 0
sArr = Split(FileName, TimeStampDelimiter)
Select Case UBound(sArr)
Case 0
cString = sArr(0)
NoStamp = Left(cString, InStrRev(cString, ".") - 1)
TimeStamp = ""
Case 1
NoStamp = sArr(0)
cString = sArr(1)
TimeStamp = Left(cString, InStrRev(cString, ".") - 1)
Case Else
For n = 0 To UBound(sArr) - 1
NoStamp = NoStamp & sArr(n) & TimeStampDelimiter
Next n
NoStamp = Left(NoStamp, Len(NoStamp) - Len(TimeStampDelimiter))
cString = sArr(UBound(sArr))
TimeStamp = Left(cString, InStrRev(cString, ".") - 1)
End Select
ws.Cells(cRow, "B").Value = TimeStamp
ws.Cells(cRow, "G").Value = NoStamp
ws.Cells(cRow, "J").Value = aWord
cRow = cRow + 1
FileName = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Files Found: " & cRow - FirstRow, vbInformation, "Success"
End Sub
I would like to be able to get file information on a list of paths that I enter into a range of cells. I also don't want to get all the Subfolders either. I have this code that works great using 1 folder path.
Sub Get_Information()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Dim last_row As Integer
sh.Rows(1).Font.Size = 18
Set fo = fso.GetFolder(sh.Range("H1").Value)
For Each f In fo.Files
last_row = sh.Range("A" & Application.Rows.Count).End(xlUp).Row + 1
sh.Range("A" & last_row).Value = f.Name
sh.Range("B" & last_row).Value = f.Type
sh.Range("C" & last_row).Value = f.Size / 1024
sh.Range("D" & last_row).Value = f.DateLastModified
Next
MsgBox ("Done")
If you have all paths in one cell, you could split the string in that cell and then loop
with an array
Sub Get_Information()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Dim pathArray as Variant
Dim SplitString as String
Dim last_row As Integer
sh.Rows(1).Font.Size = 18
SplitString = sh.Range("H1").Value
pathArray = Split(SplitString, ";") 'change to whatever seperator you are using
For each pth in pathArray
Set fo = fso.GetFolder(pth)
For Each f In fo.Files
last_row = sh.Range("A" & Application.Rows.Count).End(xlUp).Row + 1
sh.Range("A" & last_row).Value = f.Name
sh.Range("B" & last_row).Value = f.Type
sh.Range("C" & last_row).Value = f.Size / 1024
sh.Range("D" & last_row).Value = f.DateLastModified
Next f
Next pth
MsgBox ("Done")
EDIT
If you want to loop through a range of cells instead:
Sub Get_Information()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Dim c as Range
Dim last_row As Integer
sh.Rows(1).Font.Size = 18
For each pth in sh.Range("H1:H" & last_row) 'Edit range
If not pth.value = ""
Set fo = fso.GetFolder(c.Value)
For Each f In fo.Files
last_row = sh.Range("A" & Application.Rows.Count).End(xlUp).Row + 1
sh.Range("A" & last_row).Value = f.Name
sh.Range("B" & last_row).Value = f.Type
sh.Range("C" & last_row).Value = f.Size / 1024
sh.Range("D" & last_row).Value = f.DateLastModified
Next f
End If
Next pth
MsgBox ("Done")