ObjFile.Name not comapring with String in VBA Excel - vba

i have a variable String named fileName and another variable named finalDoc
i am trying to compare both but it is not working. the program does not go in the if condition
Dim fileName As String
fileName = objFile.Name
finalDoc = cellValue & "-" & Range(sheetNo).Value & ".pdf"
//The fileName and finalDoc are getting values as expected
If finalDoc = fileName Then
'MsgBox finalDoc & " " & fileName
End If
the if condition is not working. it only works if i hardcode the value in fileName like
fileName ="abc.pdf"
any suggestions, i think this is a type issue String etc. Any help would be appreciated.
Using VBA of Excel 2013

You can't compare a string using "=". You must use the StrComp command that will return an integer depending on the outcome.
More information can be found Here
But here is an example that returns a match when comparing ABC.pdf and abc.pdf:
Sub test1()
Dim fileName1 As String
Dim fileName2 As String
Dim TestComp As Integer
fileName1 = "abc.pdf"
fileName2 = "ABC.pdf"
TestComp = StrComp(fileName1, fileName2, vbTextCompare)
If TestComp = 0 Then
MsgBox ("Match!")
Else
MsgBox (fileName1 & " and " & fileName2 & " are No Match. Outcome is " & TestComp)
End If
End Sub
All you now need to do is adjust this code to suit your needs.
Basically:
Dim fileName As String
Dim TestComp As Integer
fileName = objFile.Name
finalDoc = cellValue & "-" & Range(sheetNo).Value & ".pdf"
TestComp = StrComp(fileName,finalDoc,vbTextCompare)
If TestComp = 0 Then
//Insert code to run for a correct match
Else
//Insert code to run for incorrect match
End If

Related

Save as CSV saves file with formulas as #NAME?

I have a module function in this report that concatenates certain cells:
Function AnalysisResults(Specs As Range, Results As Range)
AnalysisResults = Join(Specs) & ";" & Replace(Join(Results), ",", ".")
End Function
Private Function Join(Range As Range, Optional ByRef Delimeter As String = " ")
Dim Str As String
For Each cell In Range
If Str <> "" Then Str = Str & Delimeter
Str = Str & cell.Value
Next
Join = Str
End Function
Then i have a command button that save my file as CSV. It works, but the where the function cells are the value saved is #NAME?.
If I Save As manually as CSV comma delimited, it saves correctly and the formula values appears.
Here is the code of the CommandButton:
Dim myValue As Variant
myValue = InputBox("Specifica numele WBT-ului de descarcare:", "Save WBT with the following name", 1)
Range("L2").Value = myValue
Dim CopyToCSV()
Dim MyPath As String
Dim MyFileName As String
Sheets("Manual Discharge WBT").EnableCalculation = True
MyPath = "\\FILES\Transfer\~~TTS Import (do not delete)~~\Import Files\"
MyFileName = Range("L2") & " Discharge " & Format(CStr(Now), " dd_mm_yyyy_hh_mm")
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Sheets("Manual Discharge WBT").Copy
With ActiveWorkbook
.SaveAs Filename:= _
MyPath & MyFileName, _
FileFormat:=xlCSVWindows, _
CreateBackup:=False
.Close False
MsgBox "Fisierul tau s-a salvat ca: " & MyFileName
End With
The solution is, you will have to save your AnalysisResults and Join functions as an add-in file .xlam and add to excel at Developer->Add-ins. Doing it this way the above code worked for me when saving to CSV without #NAME?
What was happening here was that when excel is trying to save the file to CSV, it doesn't know what the AnalysisResults function is.

How to auto rename multiple files with different indexing in VB.NET

how do i auto rename multiple files that are being copied with different indexing? i mean the (0), (1), etc... i.e. if i have two files in Folder1 that has a.txt and b.txt, And another two same files inside the Folder2 And copy the a.txt and b.txt from Folder1 to Folder2 then the a.txt will become a(1).txt and the b.txt to b(1).txt. how do i do it in a single instance? what came to my mind is to have many Strings and Integers as many as the files, but i will be dealing thousands of files. This is what i have so far.
Dim ii as Integer = 0
Dim iii as Integer = 0
Sub Copy()
For i = 0 To updatedFiles.Count - 1
Dim fileName As String = Path.GetFileNameWithoutExtension(updatedFiles(i))
Dim filePath As String = Path.GetDirectoryName(updatedFiles(i))
Dim fileExt As String = Path.GetExtension(updatedFiles(i))
Dim newFile As String = filePath & "\" & fileName & "(" & ii & ")" & fileExt
Dim newFile2 As String = filePath & "\" & fileName & "(" & iii & ")" & fileExt
If File.Exists(Path.Combine(dest, updatedFiles(i))) Then
ii += 1
'Copy newFile
ElseIf File.Exists(Path.Combine(dest, newFile)) Then
iii += 1
'Copy newFile2
End If
Next
End Sub
This doesn't do it right, from the situation above, the a.txt becomes a(1).txt but the b.txt becomes b(2).txt. the result should be
a (1).txt
b (1).txt
You will need to have: Imports System.IO
When Copy() is run, all of the files from the source folder will be copied over to the destination folder, and renamed file(1).ext, file(2).ext, etc. if the file already exists in the destination folder:
Dim sourceFolder As String = "C:\Users\Public\Documents\Folder1"
Dim destFolder As String = "C:\Users\Public\Documents\Folder2"
Sub Copy()
Dim allFiles() As String 'Put all files in an array
allFiles = Directory.GetFiles(sourceFolder)
Dim i As Integer = 0 'File counter
Dim fileName As String = "" 'This will be name of file without path
Dim fileNameNoExt As String = "" 'Name of file without extension
Dim fileExt As String = "" 'File Extension
For j As Integer = 0 To allFiles.Count - 1
i = 1 're-initialize i
fileName = allFiles(j).Substring(allFiles(j).LastIndexOf("\") + 1)
fileNameNoExt = allFiles(j).Substring(allFiles(j).LastIndexOf("\"), allFiles(i).LastIndexOf(".") - allFiles(j).LastIndexOf("\"))
fileExt = allFiles(j).Substring(allFiles(j).LastIndexOf(".") + 1)
If File.Exists(destFolder & "\" & fileName) Then
While File.Exists(destFolder & "\" & fileNameNoExt & "(" & i & ")." & fileExt)
i += 1
'when while fails, i will hold the next value for file
End While
File.Copy(allFiles(j), destFolder & "\" & fileNameNoExt & "(" & i & ")." & fileExt)
Else
File.Copy(allFiles(j), destFolder & "\" & fileName)
'if there is no file with the same name, there is a direct copy of the file to the destination folder
End If
Next
End Sub
Easiest way is iterate twice. Once to add something to the name like aTBR.txt, bTBR.txt. TBR(To be renamed). You can put anything.
Second time to change name to what you would like it to be.
Harder way but maybe faster is to start with renaming last object. d.txt to e.txt?? then c.txt to d.txt, b.txt to c.txt
For that option you would need to keep their names in order in some array, or have them in alphabetic order and store their names array when you load app.
Update:
put Dim ii as Integer = 0
Dim iii as Integer = 0
inside for loop

Can not activate the file which has a variable name

I have a Project that i have to finish soon but i get error when i try to Activate an Excel file with a variable inside of its Name.I get a runtime error 9 all the time even if I tried almost every Solutions that People suggested me.Thatswhy i send you the whole link, where it can be another Problem which causes this error.
Sub M01_Neue_Maßnahme()
'Variablen definieren
Dim Ord As String
Dim mNummer As String
Dim Jahr As String
Dim Welle As String
Dim Name As String
Dim mNummerGanz As String
Dim Exportart As Integer
Dim strOrdner As String
Dim meldung As String
Dim AlterLinkKurz As String
Dim verknuepfungsname_ist As String
Dim verknuepfungsname_soll As String
Dim verknuepfungsname_soll_teil As String
Exportart = Worksheets("Vorgaben").Range("C5").Value
Ord = Worksheets("Vorgaben").Range("C4").Value
User has been asked to fill out two Input Box, which is for documenting the Excel file while saving it.
mNummer = InputBox("Bitte Maßnahmennummer eingeben")
Welle = InputBox("Bitte Welle auswählen", , "0" & Worksheets("Vorgaben").Range("B15").Value)
mNummerGanz = mNummer & "" & "" & Welle
Dim a As String
Dim b As String
AlterLinkKurz = Worksheets("Eingabefeld").Range("AO47").Value
aLinks = ActiveWorkbook.LinkSources()
If Not IsEmpty(aLinks) Then
For i = 1 To UBound(aLinks)
verknuepfungsname_ist = Mid(aLinks(i), InStrRev(aLinks(i), "\") + 1, Len(aLinks(i)) - InStrRev(aLinks(i), "\"))
verknuepfungsname_soll_teil = Mid(AlterLinkKurz, InStrRev(AlterLinkKurz, "\") + 1, Len(AlterLinkKurz) - InStrRev(AlterLinkKurz, "\"))
If verknuepfungsname_ist = verknuepfungsname_soll_teil Then
'Durch kopieren der xlsx modifizierte Links werden zurückgesetzt
If aLinks(i) <> AlterLinkKurz Then
AlterLinkKurz = aLinks(i)
End If
End If
Next i
End If
NeuerLink = Worksheets("Vorgaben").Range("C10").Value
For Each link In ActiveWorkbook.LinkSources(xlExcelLinks)
If InStr(link, AlterLinkKurz) > 0 Then
Application.DisplayAlerts = False
ActiveWorkbook.ChangeLink link, _
NeuerLink, xlLinkTypeExcelLinks
End If
Next
Saving the file with the a variable Name under "Dateiname"
If Exportart = 1 Then
If Dir(Ord, vbDirectory) <> "" Then
Else
MsgBox ("Standardpfad nicht vorhanden." & vbCr & "Datei wird im folgenden Verzeichnis abgelegt:" & vbCr & vbCr & Ord)
MkDir Ord
End If
Dateiname = Ord & mNummerGanz & "_" & Name & ".xlsm"
ThisWorkbook.SaveAs Filename:=Dateiname
Now i open a file called 1.xlsm, i want to copy a Content from this file and then activate the variable Named file and paste it on that file. But i get an error.
'Opening 1.xlsm
ChDir _
"Z:\1000_Entwicklung\05_PROJECT\0558000_CFT\055800L_CFT_Projektleitung\99_Arbeitsordner PL\Tanverdi\SummaryPPT"
Workbooks.Open Filename:= _
"Z:\1000_Entwicklung\05_PROJECT\0558000_CFT\055800L_CFT_Projektleitung\99_Arbeitsordner PL\Tanverdi\SummaryPPT\1.xlsm"
Range("G5:P41").Select
Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
I wanted to paste the content in the file which i have saved under variable Dateiname, i get runtime error 9.
Windows(Dateiname).Activate
I am sorry this could be easy to ask but i am new at VBA and Need so much your help.

Automatically create at shortcut to a file

I have a small piece of code under a command button click which saves the workbook file with a new name in a new location, I am wondering if it is possible to also automatically create a shortcut to that newly saved workbook in a different location?
Private Sub CommandButton1_Click()
Dim SelectedFNumber As String
Dim DateStr As String
Dim myFileName As String
Dim StorePath As String
DateStr = Format(Now, "dd.mm.yy HH.mm")
SelectedFNumber = Range("B4").Text
If SelectedFNumber <> "SELECT F NUMBER" And Range("D11") > "0" Then
StorePath = "G:\Targets\" & SelectedFNumber & "\"
myFileName = StorePath & SelectedFNumber & " " & DateStr & ".xlsm
If Len(Dir(StorePath, vbDirectory)) = 0 Then
MkDir StorePath
End If
ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Else
MsgBox "Select an F Number"
End If
End Sub
You basically need to add something like this:
Dim sShortcutLocation As String
sShortcutLocation = "C:\blah\workbook shortcut.lnk"
With CreateObject("WScript.Shell").CreateShortcut(sShortcutLocation)
.TargetPath = myFileName
.Description = "Shortcut to the file"
.Save
End With
changing the location to wherever you want.

Read a value from a cell without opening the Workbook [duplicate]

I found this bit of code and thought it might be good to use if I just need to pull one value from a closed sheet.
strInfoCell = "'" & strPath & "[" & strFile & "]Sheet1'!R3C3"
myvalue = ExecuteExcel4Macro(strInfoCell)
When I run this code I get a value for strinfocell of
'C:\Users\my.name\Desktop[QOS DGL stuff.xlsx]Sheet1'!R3C3
But when I run the code a dialogue pops up, showing desktop files with "QOS DGL suff" showing.
What's causing this, why is it not just pulling back the data as expected?
I know the path and file name are right, because if I copy them from the debug output and paste them in to start>>run then the correct sheet opens.
I know that Sheet1 (named: ACL), does have a value in cells(3,3)
It depends on how you use it. The open file dialog box is being showed to you because the "strPath" doesn't have a "" in the end ;)
Try this code.
Option Explicit
Sub Sample()
Dim wbPath As String, wbName As String
Dim wsName As String, cellRef As String
Dim Ret As String
'wbPath = "C:\Documents and Settings\Siddharth Rout\Desktop\"
wbPath = "C:\Users\my.name\Desktop\"
wbName = "QOS DGL stuff.xls"
wsName = "ACL"
cellRef = "C3"
Ret = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, -4150)
MsgBox ExecuteExcel4Macro(Ret)
End Sub
Similar application, but no hard coded paths as in the examples above. This function copies the value from another closed workbook, similar to the =INDIRECT() function, but not as sophisticated. This only returns the value...not a reference..so it cannot be used with further functions which require references (i.e.: VLOOKUP()). Paste this code into a new VBA module:
'Requires filename, sheetname as first argument and cell reference as second argument
'Usage: type in an excel cell -> =getvalue(A1,B1)
'Example of A1 -> C:\TEMP\[FILE1.XLS]SHEET1'
'Example of B1 -> B3
'This will fetch contents of cell (B3) located in (sheet1) of (c:\temp\file1.xls)
'Create a module and paste the code into the module (e.g. Module1, Module2)
Public xlapp As Object
Public Function getvalue(ByVal filename As String, ref As String) As Variant
' Retrieves a value from a closed workbook
Dim arg As String
Dim path As String
Dim file As String
filename = Trim(filename)
path = Mid(filename, 1, InStrRev(filename, "\"))
file = Mid(filename, InStr(1, filename, "[") + 1, InStr(1, filename, "]") - InStr(1, filename, "[") - 1)
If Dir(path & file) = "" Then
getvalue = "File Not Found"
Exit Function
End If
If xlapp Is Nothing Then
'Object must be created only once and not at each function call
Set xlapp = CreateObject("Excel.application")
End If
' Create the argument
arg = "'" & filename & "'!" & Range(ref).Range("A1").Address(, , xlR1C1)
'Execute an XLM macro
getvalue = xlapp.ExecuteExcel4Macro(arg)
End Function
Code above
strInfoCell = "'" & strPath & "[" & strFile & "]Sheet1'!R3C3"
myvalue = ExecuteExcel4Macro(strInfoCell)
Should read
strInfoCell = "'" & strPath & "[" & strFile & "]" & "Sheet1'!R3C3"
myvalue = ExecuteExcel4Macro(strInfoCell)
It is missing " & "
No need for a function
Cheers
Neil
Data = "'" & GetDirectory & "[" & GetFileName & "]" & Sheet & "'!" & Range(Address).Range("A1").Address(, , xlR1C1)
Address = "$C$3"
GetDirectory = "C:\Users\my.name\Desktop\"
GetFileName = "QOS DGL stuff.xlsx"
Sheet = "ACL"