VBA codes not running after re-installed windows10 - excel

I have already run these codes successfully more than 200 times as I download files on daily basis.
Also having another copies of same code in different drives as reference in case of any issue.
Last night I re-installed my Win10 and office 2019 pro plus both are updated to latest.
And now the codes are not running.
I am not a hard core programmer, not able to understand what's wrong with them. Do I need to install any reference library or .net framework or something else.
The codes stopped at
"Name oldFullName As newfullname"
2 files are there do be downloaded and renamed
The codes get 1st file successfully but, do not rename it so not going to 2nd loop to download 2nd file and to further rename that.
Public IsExit As Boolean
Global Path As String
Private Sub Download_AllZip()
Path = ThisWorkbook.Worksheets("Downloads").Range("C3").Value
Application.ScreenUpdating = FALSE
Application.EnableEvents = FALSE
Dim LR As Long
Dim Fileurl As String, Filename As String, y As String, z As String 'msg as string
Dim r As Long
LR = Sheets("Downloads").Range("C6").Row
For r = 5 To LR
Fileurl = Sheets("Downloads").Range("C" & r).Value
If InStr(1, Fileurl, ".zip") <> 0 Then
filepath = Path
End If
Dim Obj1 As Object
Set Obj1 = CreateObject("Microsoft.XMLHTTP")
Obj1.Open "GET", Fileurl, FALSE
Obj1.send
If Obj1.Status = 200 Then
Set Obj2 = CreateObject("ADODB.Stream")
Obj2.Open
Obj2.Type = 1
Obj2.Write Obj1.responseBody
Obj2.SaveToFile (filepath & getfilename(Fileurl)), 2 ' 1 = no overwrite, 2 = overwrite
Call UnzipFileRename(filepath & getfilename(Fileurl), filepath, Sheets("Downloads").Range("D" & r).Value)
Obj2.Close
y = (y & vbCr & Sheets("Downloads").Range("D" & r).Value & " = Downloaded & Converted To .CSV in " & filepath)
ThisWorkbook.Sheets("Downloads").Range("E" & r).Value = "Downloaded" '/STATUS
Else
z = (z & vbCr & Sheets("Downloads").Range("D" & r).Value & " = Failed To Download")
ThisWorkbook.Sheets("Downloads").Range("E" & r).Value = "Failed" '/STATUS
End If
Next r
End Sub
Function getfilename(filepath As String)
Dim v_string() As String
v_string = Split(filepath, "/")
getfilename = v_string(UBound(v_string))
End Function
Private Sub UnzipFileRename(zipFullName As Variant, unzipPath As Variant, newName As String)
Dim ShellApp As Object, oldFullName As String, newfullname As String, n As Variant
Set ShellApp = CreateObject("Shell.Application")
'/get file name
For Each n In ShellApp.Namespace(zipFullName).Items
a = a + 1
oldFullName = unzipPath & n.Name
newfullname = unzipPath & newName
If a = 1 Then Exit For
Next n
'/delete previous version to avoid any issues
DeleteFile oldFullName
DeleteFile newfullname
'/unzip the file
ShellApp.Namespace(unzipPath).CopyHere ShellApp.Namespace(zipFullName).Items
'/rename the file
Name oldFullName As newfullname
'/delete zip file
DeleteFile CStr(zipFullName)
End Sub
Private Sub DeleteFile(PathAndName As String)
On Error Resume Next
Kill PathAndName
On Error GoTo 0
End Sub

Related

page sizing & handling on acrobar pro dc via vba excel

I have managed convert a list of images onto pdf, then gathered them in a single file and then print them as multiple pages 10 columns x 14 rows so I can print in a single sheet 140 original images.
All of these with sendkeys method which was absolutely madness and frustrating but at the end it works pretty fine, the only handicap is that I have to do this almost everyday and once I run the sendkeys macro I can't do nothing with my computer until it ends which could probably be hours
I'm trying to do this in a less "messy" way
I have managed to convert the images in pdf easely with this code I modified from a search on internet (just in case someone find it usefull for him/her)
Sub png_to_pdf()
Dim Acroapp As New Acrobat.Acroapp
Dim pddoc As New Acrobat.AcroPDDoc
Set Acroapp = CreateObject("AcroExch.App")
Set pddoc = CreateObject("AcroExch.pddoc")
aux_pngtopdf "F:\ES-VAL\PURCH-U\CARLOS\qr", pddoc
End Sub
Private Sub aux_pngtopdf(ByVal xFolderName As String, ByVal pddoc As Object)
Dim xFileSystemObject As Object
Dim xFolder As Object
Dim xSubFolder As Object
Dim xFile As Object
Dim xfilepdf As String
Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
Set xFolder = xFileSystemObject.GetFolder(xFolderName)
For Each xFile In xFolder.Files
If Right(xFile, 3) = "png" And Application.CountIf(Columns(10), Mid(xFolderName, 29, 9)) = 0 And Application.CountIf(Columns(11), Mid(xFolderName, 29, 9)) = 0 Then
pddoc.Open xFile
xfilepdf = Left(xFile, Len(xFile) - 3) & "pdf"
pddoc.Save PDSaveFull, xfilepdf
End If
Next xFile
For Each xSubFolder In xFolder.subfolders
If Len(xSubFolder) < 250 Then
aux_pngtopdf xSubFolder.Path, pddoc
End If
Next xSubFolder
Set xFile = Nothing
Set xFolder = Nothing
Set xFileSystemObject = Nothing
End Sub
I'm changing the code I found (I don't really remember if here or if in any other site) to merge all the pdf into a single one and it seems it would be fine
Sub merge_pdf()
Const DestFile As String = "MergedFile.pdf" ' <-- change to suit
Dim MyPath As String, MyFiles As String
Dim a() As String, i As Long, f As String
Dim j As Integer
j = 4
' Choose the folder or just replace that part by: MyPath = Range("E3")
With Application.FileDialog(msoFileDialogFolderPicker)
'.InitialFileName = "C:\Temp\"
.AllowMultiSelect = False
If .Show = False Then Exit Sub
MyPath = .SelectedItems(1) & "\" & Cells(j, 3).Value
DoEvents
End With
' Populate the array a() by PDF file names
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
ReDim a(1 To 2 ^ 14)
f = Dir(MyPath & "*.pdf")
While Len(f)
If StrComp(f, DestFile, vbTextCompare) Then
i = i + 1
a(i) = f
End If
f = Dir()
Wend
' Merge PDFs
If i Then
ReDim Preserve a(1 To i)
MyFiles = Join(a, ",")
Application.StatusBar = "Merging, please wait ..."
Call aux_MergePDFs(MyPath, MyFiles, DestFile)
Application.StatusBar = False
Else
MsgBox "No PDF files found in" & vbLf & MyPath, vbExclamation, "Canceled"
End If
End Sub
Private Sub aux_MergePDFs(MyPath As String, MyFiles As String, Optional DestFile As String = "MergedFile.pdf")
Dim a As Variant, i As Long, n As Long, ni As Long, p As String
Dim Acroapp As New Acrobat.Acroapp, PartDocs() As Acrobat.CAcroPDDoc
If Right(MyPath, 1) = "\" Then p = MyPath Else p = MyPath & "\"
a = Split(MyFiles, ",")
ReDim PartDocs(0 To UBound(a))
On Error GoTo exit_
If Len(Dir(p & DestFile)) Then Kill p & DestFile
For i = 0 To UBound(a)
' Check PDF file presence
If Dir(p & Trim(a(i))) = "" Then
MsgBox "File not found" & vbLf & p & a(i), vbExclamation, "Canceled"
Exit For
End If
' Open PDF document
Set PartDocs(i) = CreateObject("AcroExch.PDDoc")
PartDocs(i).Open p & Trim(a(i))
If i Then
' Merge PDF to PartDocs(0) document
ni = PartDocs(i).GetNumPages()
If Not PartDocs(0).InsertPages(n - 1, PartDocs(i), 0, ni, True) Then
MsgBox "Cannot insert pages of" & vbLf & p & a(i), vbExclamation, "Canceled"
End If
' Calc the number of pages in the merged document
n = n + ni
' Release the memory
PartDocs(i).Close
Set PartDocs(i) = Nothing
Else
' Calc the number of pages in PartDocs(0) document
n = PartDocs(0).GetNumPages()
End If
Next
If i > UBound(a) Then
' Save the merged document to DestFile
If Not PartDocs(0).Save(PDSaveFull, p & DestFile) Then
MsgBox "Cannot save the resulting document" & vbLf & p & DestFile, vbExclamation, "Canceled"
End If
End If
exit_:
' Inform about error/success
If Err Then
MsgBox Err.Description, vbCritical, "Error #" & Err.Number
ElseIf i > UBound(a) Then
MsgBox "The resulting file is created:" & vbLf & p & DestFile, vbInformation, "Done"
End If
' Quit Acrobat application
Acroapp.Exit
Set Acroapp = Nothing
End Sub
But I don't have any clue on how to print several pages of the pdf into a single one. Not interested in only 16 pages per sheet (since the images I try to print are QR codes 12mmx12mm so it fits pretty fine 140 of them in a single sheet) which could be more or less easy if you set adobe pdf as your default printer and setup it to print 16 pages per sheet (I also found part of a code that could fit to this purpose)
Any clue will be apreciated
Thanks

Split PDF into new files per page - Excel VBA

I am trying to split a pdf into multiple new files per page.
I found this code on Excel Forum
I modified it to to suit my folder path and file.
I have also added the Acrobat.tdl library to references.(Don't have the actual acrobat pro installed. Followed the steps suggested in this link)
However, when I try to run the code, I get the error - Run-time error '429': ActiveX component can't create object.
The error occurs on the line Set PDDoc = CreateObject("AcroExch.pdDoc")
Here is the full code:
Sub SplitPDF()
Dim PDDoc As Acrobat.CAcroPDDoc, newPDF As Acrobat.CAcroPDDoc
Dim PDPage As Acrobat.CAcroPDPage
Dim thePDF As String, PNum As Long
Dim f As String, i As Integer, Result As Variant, NewName As String
f = ThisWorkbook.Path & "\"
thePDF = f & "CDE_9740240D_2020-09-08.pdf"
Set PDDoc = CreateObject("AcroExch.pdDoc")
Result = PDDoc.Open(thePDF)
If Not Result Then
MsgBox "Can't open file: " & thePDF
Exit Sub
End If
'...
PNum = PDDoc.GetNumPages
For i = 0 To PNum - 1
Set newPDF = CreateObject("AcroExch.pdDoc")
newPDF.Create
NewName = f & " Page_" & i & "_of_" & PNum & ".pdf"
newPDF.InsertPages -1, PDDoc, i, 1, 0
newPDF.Save 1, NewName
newPDF.Close
Set newPDF = Nothing
Next i
End Sub
Can someone please help me make this code work.

How to save the active workbook in another folder in Excel VBA?

I am trying to automatically save my active workbook into another folder on my computer and if there is already a file with the name of my workbook in that folder, then it should be saved with "_v1"/"_v2" and so on at the end of its name.
I have found this code but it works just for the current folder, where the workbook is saved.
Sub SaveNewVersion_Excel()
Dim FolderPath As String
Dim myPath As String
Dim SaveName As String
Dim SaveExt As String
Dim VersionExt As String
Dim Saved As Boolean
Dim x As Long
TestStr = ""
Saved = False
x = 2
VersionExt = "_v"
On Error GoTo NotSavedYet
myPath = "O:\Operations\Department\Data Bank Coordinator\_PROJECTS_\QC BeadRegion Check\Multi Ref Archiv"
myFileName = Mid(myPath, InStrRev(myPath, "\") + 1, InStrRev(myPath, ".") - InStrRev(myPath, "\") - 1)
FolderPath = Left(myPath, InStrRev(myPath, "\"))
SaveExt = "." & Right(myPath, Len(myPath) - InStrRev(myPath, "."))
On Error GoTo 0
If InStr(1, myFileName, VersionExt) > 1 Then
myArray = Split(myFileName, VersionExt)
SaveName = myArray(0)
Else
SaveName = myFileName
End If
If FileExist(FolderPath & SaveName & SaveExt) = False Then
ActiveWorkbook.saveAs FolderPath & SaveName & SaveExt
Exit Sub
End If
Do While Saved = False
If FileExist(FolderPath & SaveName & VersionExt & x & SaveExt) = False Then
ActiveWorkbook.saveAs FolderPath & SaveName & VersionExt & x & SaveExt
Saved = True
Else
x = x + 1
End If
Loop
Exit Sub
NotSavedYet:
MsgBox "This file has not been initially saved. " & _
"Cannot save a new version!", vbCritical, "Not Saved To Computer"
End Sub
Function FileExist(FilePath As String) As Boolean
Dim TestStr As String
On Error Resume Next
TestStr = Dir(FilePath)
On Error GoTo 0
If TestStr = "" Then
FileExist = False
Else
FileExist = True
End If
End Function
It works for the current folder but when I change the folder path it doesn't work.
I would very much appreciate it if you could help me.
Thanks!
Sergiu
I've assumed the new folder is "D:_PROJECTS_\Multi Ref Archiv" and that if the existing file is zzzz_v07.xlsm then you want this saved as zzzz_v08.xlsm even when there are no previous versions in the folder. I added the leading zero so they sort nicely!
Sub SaveNewVersion_Excel2()
Const FOLDER = "D:\_PROJECTS_\Multi Ref Archiv" ' new location
Const MAX_FILES = 99
Dim oFSO As Object, oFolder As Object, bOK As Boolean, res As Variant
Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim sFilename As String, sFilename_v As String
' filename only
sFilename = ThisWorkbook.Name
' check folder exists
If Not oFSO.folderexists(FOLDER) Then
bOK = MsgBox(FOLDER & " does not exist. Do you want to create ?", vbYesNo, "Confirm")
If bOK Then
oFSO.createFolder FOLDER
MsgBox "OK created " & FOLDER, vbInformation
Else
Exit Sub
End If
End If
' get next name
sFilename_v = Next_v(sFilename)
' check if exists
Dim i As Integer: i = 1
Do While oFSO.fileexists(FOLDER & "\" & sFilename_v) = True And i <= MAX_FILES
i = i + 1
sFilename_v = Next_v(sFilename_v)
Loop
' check loop ok
If i > MAX_FILES Then
MsgBox "More than " & MAX_FILES & " files already exist", vbExclamation
Exit Sub
End If
sFilename_v = FOLDER & "\" & sFilename_v
' confirm save
res = MsgBox("Do you want to save to " & sFilename_v, vbYesNo, "Confirm")
If res = vbYes Then
ActiveWorkbook.SaveAs sFilename_v
MsgBox "Done", vbInformation
End If
End Sub
Function Next_v(s As String)
Const ver = "_v"
Dim i As Integer, j As Integer, ext As String, rev As Integer
i = InStrRev(s, ".")
j = InStrRev(s, ver)
ext = Mid(s, i)
' increment existing _v if exists
If j > 0 Then
rev = Mid(s, j + 2, i - j - 2)
s = Left(s, j - 1)
Else
rev = 0
s = Left(s, i - 1)
End If
Next_v = s & ver & Format(rev + 1, "00") & ext
End Function
You can move all of the logic out to a separate function, then you only need to call that to get the "correct" name to save as.
'Pass in the full path and filename
' Append "_Vx" while the passed filename is found in the folder
' Returns empty string if the path is not valid
Function NextFileName(fPath As String)
Const V As String = "_V"
Dim fso, i, p, base, ext
Set fso = CreateObject("scripting.filesystemobject")
'valid parent folder?
If fso.folderexists(fso.GetParentFolderName(fPath)) Then
p = fPath
ext = fso.getextensionname(p)
base = Left(p, Len(p) - (1 + Len(ext))) 'base name without extension
i = 1
Do While fso.fileexists(p)
i = i + 1
p = base & (V & i) & "." & ext
Loop
End If
NextFileName = p
End Function

Excel VBA macro dir() function incorrect return value when folder is empty

Trying to use the DIR function in a Macro to determine whether a folder exists. Have found the following code
Function FileOrFolderExistsOnMac(FileOrFolderstr As String) As Boolean
Ron de Bruin : 1-Feb-2019
Function to test whether a file or folder exist on a Mac in office 2011 and up
'Uses AppleScript to avoid the problem with long names in Office 2011,
'limit is max 32 characters including the extension in 2011.
Dim ScriptToCheckFileFolder As String
Dim TestStr As String
If Val(Application.Version) < 15 Then
ScriptToCheckFileFolder = "tell application " & Chr(34) & "System Events" & Chr(34) & _
"to return exists disk item (" & Chr(34) & FileOrFolderstr & Chr(34) & " as string)"
FileOrFolderExistsOnMac = MacScript(ScriptToCheckFileFolder)
Else
On Error Resume Next
TestStr = Dir(FileOrFolderstr & "*", vbDirectory)
On Error GoTo 0
If Not TestStr = vbNullString Then FileOrFolderExistsOnMac = True
End If
End Function
from
https://www.rondebruin.nl/win/s9/win003.htm
However, when the folder in the path location is empty, the function determines that the path directory does not exist.
Thank you for the post, it helped me identify the source of my problem.
I modified my often-used function to account for this quirk.
Here's a modified function that should work for empty folders (works on Windows, not tested on Macs).
Function directoryExists(ByVal dirPath As String) As Boolean
'amy#logicallytech.com
'7/15/2022
directoryExists = (Dir(dirPath) <> "")
If directoryExists Then Exit Function
'If folder is empty, above will show it does not exist, so just to confirm...
Dim strParentFolder As String
Dim strSubFolder As String
Dim myfso As Object
Dim parentFolder As Object
Dim subFolder As Object
If InStr(dirPath, "\") > 0 Then
If Right(dirPath, 1) = "\" Then dirPath = Left(dirPath, Len(dirPath) - 1)
strParentFolder = Left(dirPath, InStrRev(dirPath, "\", , vbTextCompare))
strSubFolder = Right(dirPath, Len(dirPath) - InStrRev(dirPath, "\", , vbTextCompare))
ElseIf InStr(dirPath, "/") > 0 Then
If Right(dirPath, 1) = "/" Then dirPath = Left(dirPath, Len(dirPath) - 1)
strParentFolder = Left(dirPath, InStrRev(dirPath, "/", , vbTextCompare))
strSubFolder = Right(dirPath, Len(dirPath) - InStrRev(dirPath, "/", , vbTextCompare))
End If
Set myfso = CreateObject("Scripting.FileSystemObject")
Set parentFolder = myfso.GetFolder(strParentFolder)
For Each subFolder In parentFolder.SubFolders
If LCase(Trim(subFolder.Name)) = LCase(Trim(strSubFolder)) Then
directoryExists = True
GoTo CleanUp
End If
Next subFolder
CleanUp:
Set subFolder = Nothing
Set parentFolder = Nothing
Set myfso = Nothing
End Function

Check if file downloaded to resume the code

I have a code that enables me to login a website with credentials. I have replaced those with hidden1, hidden2 and hidden3 in the code for privacy.
The code login to the website then navigate to specific page that has two drop down lists.
From the first list that has four options (this is fixed to four options), I select an option and after that the second drop down is updated according to list1
But List2 is changeable as the options are not known
The next step is to click a button that goes to another page with two elements that I clicked so as to export a pdf file.
Everything is fine till now.
The problem is that I have put waiting line for 15 seconds so as to wait for the download and I am searching for more efficient way to check if the file downloaded or not using selenium vba.
Here's the code
Private Sub Test()
Dim bot As New Selenium.WebDriver
Dim sList1 As SelectElement
Dim sList2 As SelectElement
Dim By As New By
Dim fso As Object
Dim myFolder As Object
Dim objFile As Object
Dim fil As String
Dim fn As String
Dim dteFile As Date
Dim n As Integer
Dim x As Integer
Dim j As Integer
Const DOWNLOAD_DIRECTORY As String = "C:\Users\Future\Desktop\Files"
Set fso = CreateObject("Scripting.FileSystemObject")
If Len(Dir(DOWNLOAD_DIRECTORY, vbDirectory)) = 0 Then MkDir DOWNLOAD_DIRECTORY
With bot
.SetPreference "download.default_directory", DOWNLOAD_DIRECTORY
.SetPreference "download.directory_upgrade", True
.SetPreference "download.prompt_for_download", False
.Start "chrome", "http://primprep.emis.gov.eg"
.Get "/"
.FindElementById("ContentPlaceHolder1_TextBox1").SendKeys "hidden1"
.FindElementById("ContentPlaceHolder1_TextBox3").SendKeys "hidden2"
.FindElementById("ContentPlaceHolder1_TextBox2").SendKeys "hidden3"
.FindElementById("ContentPlaceHolder1_Button2").Click
.FindElementById("Button1").Click
.Wait 1000
mLoop:
n = n + 1
If n = 5 Then Stop
x = 0
sPoint:
Set sList1 = .FindElementById("ContentPlaceHolder1_Dedara").AsSelect
sList1.SelectByIndex n
.Wait 2000
Set sList2 = .FindElementById("ContentPlaceHolder1_Dschool").AsSelect
For j = x + 1 To sList2.Options.Count
If x + 1 >= sList2.Options.Count Then GoTo mLoop
fil = Format(n, "00") & "-" & Format(j, "00") & "-" & Application.Trim(sList2.Options(j + 1).Text) & ".pdf"
sList2.SelectByIndex j
.FindElementById("ContentPlaceHolder1_Button1").Click
.Wait 2000
If .IsElementPresent(By.ID("ContentPlaceHolder1_Label2")) Then
If .FindElementById("ContentPlaceHolder1_Label2").Text = "لا يوجد بيانات لعرضها" Then
Debug.Print "No Data For This School >> " & Application.Trim(Replace(fil, ".pdf", ""))
x = x + 1
GoTo sPoint
End If
End If
Do
Loop While .FindElementsById("IconImg_CrystalReportViewer1_toptoolbar_print").Count = 0
.FindElementById("IconImg_CrystalReportViewer1_toptoolbar_print").Click
Do
Loop While .FindElementsByCss("[id^='theBttnbobjid']").Count = 0
.FindElementByCss("[id^='theBttnbobjid']").Click
Application.Wait Now + TimeSerial(0, 0, 15)
'I need a way to check if the file downloaded or not instead of waiting for 15 seconds
'as sometimes the file took no time and sometimes the file may took over 15 seconds
Set myFolder = fso.GetFolder(DOWNLOAD_DIRECTORY)
dteFile = DateSerial(1900, 1, 1)
For Each objFile In myFolder.Files
If objFile.DateLastModified > dteFile And fso.GetExtensionName(objFile.Path) = "pdf" Then
dteFile = objFile.DateLastModified
fn = objFile.name
End If
Next objFile
If fn <> vbNullString And Not fso.FileExists(DOWNLOAD_DIRECTORY & "\" & fil) Then
fso.MoveFile DOWNLOAD_DIRECTORY & "\" & fn, DOWNLOAD_DIRECTORY & "\" & fil
End If
.FindElementById("ContentPlaceHolder1_Button2").Click
.Wait 2000
x = x + 1
GoTo sPoint
Next j
GoTo mLoop
End With
End Sub
I have searched for such a topic and found a link but it was for Java selenium. And I need to deal with VBA selenium.
Regards
you can check for files count in DOWNLOAD_DIRECTORY before download procedure code and then check again after it. If the count increased by one, so it is downloaded.
just an IDEA
i found a code that i used to count files for attendance . you can take an advantage of it
Sub Attfiles()
Dim AttFolder As String, path As String, count As Integer
AttFolder = "D:\attdata"
path = AttFolder & "\*.xls" 'ممكن تغير الامتداد هنا
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
Range("A5").Value = count
End Sub

Resources