Excel VBA - Runtime error 1004 file could not be found - excel

In a part of my program, I want to open existing Excel files via VBA in order to modify it and manipulate data.
'Declaration des variables d'objects Excel
Dim wb As Workbook
Dim ws As Worksheet
Dim Fname As String
'Declaration des variables de calcul
Dim a As Double
Dim numimpact, nummatrix, debut, fin, e, n As Long
Dim i As Boolean
'Initialisation des variables
i = True
a = 0
e = 1
numimpact = 1
nummatrix = 1
debut = 2
n = 1000
fin = debut + n
'Boucle de lecture de tous les fichiers Excel
Do While i = True
'Test et incrementation des fichiers Excel
If numimpact < 7 Then
'Ouverture fichiers
Fname = "D:\mmLaurencon\Desktop\NL\Test\CFRP1\"
Set wb = Workbooks.Open(Fname & "CFRP1-" & nummatrix & "-" & numimpact & ".xlsm")
'Set wb = Workbooks.Open("D:\mmLaurencon\Desktop\NL\Test\CFRP 1\CFRP1-1-" & numimpact)
Set ws = wb.Worksheets(1)
'Parcourir colonne B
Do While Cells(e, 2).Value <> ""
For Each e In Columns(2)
Cells(fin, 3).Value = Application.Sum(Cells(debut, 2).Value, Cells(fin, 2).Value) / n
debut = debut + 1
fin = fin + 1
e = e + 1
'save the file
ActiveWorkbook.SaveAs Filename:= _
"D:\mmLaurencon\Desktop\NL\Test\CFRP " & nummatrix & "\CFRP1-1-" & numimpact & ".xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
'close the file
wb.Close
Next
numimpact = numimpact + 1
Loop
ElseIf numimpact = 7 Then
nummatrix = nummatrix + 1
numimpact = 1
ElseIf nummatrix = 10 Then
i = False
End If
Loop
I made this code, but a runtime error 1004 File could not be found appears on line Set wb = Workbooks.Open (Fname & "CFRP1-" & nummatrix & "-" & numimpact & ".xlsm"). I don't understand why as I indicated the right path and file. I tried another way of doing this Set wb = Workbooks.Open("D:\mmLaurencon\Desktop\NL\Test\CFRP 1\CFRP1-1-" & numimpact) but a new runtime error 1004 the document may be read-only or encrypted appears.
Have you an idea about what is going wrong? Thank you in advance!

This line Set wb = Workbooks.Open(Fname & "CFRP1-" & nummatrix & "-" & numimpact & ".xlsm") is trying to open file D:\mmLaurencon\Desktop\NL\Test\CFRP1\CFRP1-1-1.xlsm and is entirely different to your second attempt Set wb = Workbooks.Open("D:\mmLaurencon\Desktop\NL\Test\CFRP 1\CFRP1-1-" & numimpact).
The second attempt is missing the file extension, and the file path is different. The file path differs at this point D:\mmLaurencon\Desktop\NL\Test\CFRP1 compared to D:\mmLaurencon\Desktop\NL\Test\CFRP 1
I assume that both attempts were supposed to open the same file? You will need to correct the file paths - I'm not sure which is the correct one.

Related

Application.Run skipping on 2nd loop run

I am trying to create a macro which will open up an Excel file and run a macro in the newly opened file which will then generate a PowerPoint presentation, save the presentation, close the presentation, PowerPoint and the newly opened Excel file, then start the process and complete the process again with the next Excel file to be opened.
Process works fine for the first file but for the 2nd Excel file to be opened, it appears that the Application.Run code skips and so the process breaks at the Set PPPRes because there isn't a presentation to be made active as one isn't created in the Application.Run process.
Any suggestions as to why it might be breaking?
Sub CreatePowerPoints()
Dim wb As Workbook, wb1 As Workbook, PPApp As PowerPoint.Application, PPPRes As PowerPoint.Presentation
lr = Sheet1.Cells(Rows.Count, 2).End(xlUp).Row
Year1 = Right(Date, 4) - 1
Year2 = Right(Date, 4)
RepPer = Left(Sheet1.Range("REPPERIOD").Value, 3)
RepTem = Sheet1.Range("REPTEMPLATE")
Set wb1 = ThisWorkbook
For x = 6 To lr
ChkPath1b = wb1.Sheets("Tracking").Range("P" & x) & Year1 & "\" & wb1.Sheets("Tracking").Range("REPMONTH")
ChkPath2b = wb1.Sheets("Tracking").Range("P" & x) & Year2 & "\" & wb1.Sheets("Tracking").Range("REPMONTH")
If Sheet1.Range("J" & x) = "Yes" Then
Set wb1 = ThisWorkbook
wbName = wb1.Sheets("Tracking").Range("D" & x) & " - Client Engine.xlsm"
If RepPer = "Dec" Then
Filename = ChkPath1b & "\" & wbName
Set wb = Workbooks.Open(Filename, ReadOnly:=True)
End If
If RepPer <> "Dec" Then
Filename = ChkPath2b & "\" & wbName
Set wb = Workbooks.Open(Filename, ReadOnly:=True)
End If
Application.Run "'" & wbName & "'!SendToPPT"
Set PPApp = New PowerPoint.Application
Set PPPRes = PPApp.ActivePresentation
If RepPer = "Dec" Then
PPPRes.SaveAs ChkPath1b & "\" & wb1.Sheets("Tracking").Range("D" & x) & " - Monthly Report.pptm"
Else
PPPRes.SaveAs ChkPath2b & "\" & wb1.Sheets("Tracking").Range("D" & x) & " - Monthly Report.pptm"
End If
'wbName = Nothing
wb.Close False
PPPRes.Close
PPApp.Quit
wb1.Sheets("Tracking").Range("H" & x).Value = "REPORT CREATED"
wb1.Sheets("Tracking").Range("j" & x).Value = "No"
End If
Next x
MsgBox "All PowerPoints created."
End Sub

I want to replace a number with a variable that is linked with a Cell input, but i get an error

I already posted the question with only particles of my code. I want to replace the 0.5 in the following formula with my double variable z.
.Cells(21, 6).Formula = "=AVERAGEIF(RC[-4]:R[" & Total & "]C[-4],"">""&0.5*MAX(RC[-4]:R[" & Total & "]C[-4]))"
My whole code looks like this:
Sub ImportMultipleTextFile()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim InputTextFile As Variant
Dim SourceDataFolder As String
Dim OutputDataFolder As String
Dim wb As Workbook: Set wb = ThisWorkbook
Dim LastRow As Integer
Dim MyFolder As String
Dim x As Integer
Dim Total As Long
x = 3
Dim Dateiname As String
Dim z As Double
z = Worksheets(1).Range("O1").Value
If MsgBox("Kistler Drehdaten?", vbYesNo) = vbYes Then
MsgBox "Wähle den Kistler Ordner aus mit den .txt Dateien"
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
MyFolder = .SelectedItems(1)
Err.Clear
End With
SourceDataFolder = MyFolder
'Loop through each text file in source folder
InputTextFile = Dir(SourceDataFolder & "\*.txt")
While InputTextFile <> ""
Workbooks.OpenText Filename:=SourceDataFolder & "\" & InputTextFile, DataType:=xlDelimited, Tab:=True
Dateiname = ActiveWorkbook.Name
Range("A:E").Copy
wb.Worksheets(1).Range("A:E").PasteSpecial
Total = wb.Worksheets(1).Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
Dim avgSourceRangePart As String
avgSourceRangePart = "RC[-4]:R[" & Total & "]C[-4]"
Dim maxPart As String
maxPart = "MAX(RC[-4]:R[" & Total & "]C[-4])"
Dim avgConditionPart As String
avgConditionPart = """>"" & " & z & " * " & maxPart & ")"
With wb.Worksheets(1)
.Cells(21, 6).Formula = "=AVERAGEIF(RC[-4]:R[" & Total & "]C[-4],"">""&0.5*MAX(RC[-4]:R[" & Total & "]C[-4]))"
'.Cells(21, 7).Formula = "=AVERAGEIF(RC[-4]:R[" & Total & "]C[-4],"">"" &" & z & "*MAX(RC[-4]:R[" & Total & "]C[-4]))"
'.Cells(21, 7).Formula = "=AVERAGEIF(RC[-4]:R[" & Total & "]C[-4],"">"" &" & z & "*MAX(RC[-4]:R[" & Total & "]C[-4]))"
.Cells(21, 7).FormulaR1C1 = "=AVERAGEIF(" & avgSourceRangePart & ";" & avgConditionPart & ")"
.Cells(21, 8).Formula = "=AVERAGEIF(RC[-4]:R[" & Total & "]C[-4],"">""&0.5*MAX(RC[-4]:R[" & Total & "]C[-4]))"
.Range("F21:H21").Copy
End With
x = x + 1
Range("A:I").Clear
'Close the opened input file
Workbooks(InputTextFile).Close
InputTextFile = Dir
Wend
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End If
End Sub
....followed by another elseif with the same style for different text packages that need to be opened.
Continuing from my previous answer -
The line you're looking for is:
"=AVERAGEIF(RC[-4]:R[" & Total & "]C[-4],"">"" &" & z & "*MAX(RC[-4]:R[" & Total & "]C[-4]))"
But there are other problems with the code that cause errors.
The main problem was with Range("A:E").Copy. The range was not qualified, meaning it was referring to the wrong book. See the corrected code below:
Sub ImportMultipleTextFile()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim InputTextFile As Variant
Dim SourceDataFolder As String
Dim OutputDataFolder As String
Dim wb As Workbook: Set wb = ThisWorkbook
Dim LastRow As Integer
Dim MyFolder As String
Dim x As Integer: x = 3
Dim Total As Long
Dim TxtFile As Workbook
Dim z As Double
z = Worksheets(1).Range("O1").Value
If MsgBox("Kistler Drehdaten?", vbYesNo) = vbYes Then
MsgBox "Wähle den Kistler Ordner aus mit den .txt Dateien"
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
MyFolder = .SelectedItems(1)
Err.Clear
End With
SourceDataFolder = MyFolder
'Loop through each text file in source folder
InputTextFile = Dir(SourceDataFolder & "\*.txt")
While InputTextFile <> ""
Workbooks.OpenText Filename:=SourceDataFolder & "\" & InputTextFile, DataType:=xlDelimited, Tab:=True
Set TxtFile = Application.Workbooks(InputTextFile)
TxtFile.Sheets(1).Range("A:E").Copy
wb.Worksheets(1).Range("A:E").PasteSpecial
Total = wb.Worksheets(1).Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
With wb.Worksheets(1)
.Cells(21, 6).Formula = "=AVERAGEIF(RC[-4]:R[" & Total & "]C[-4],"">"" &" & z & "*MAX(RC[-4]:R[" & Total & "]C[-4]))"
.Range("F21:H21").Copy
End With
Range("A:I").Clear
'Close the opened input file
TxtFile.Close
InputTextFile = Dir
Wend
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

How to export sheet/column in VBA to XML in UTF-8 formatting

I have written a macro that outputs xml-lines (with the right formatting) in column A of a certain sheet. So each row in that sheet should correspond to 1 line in an xml-file. If I copy-paste this column in notepad en save it as .xml (after removing the "-tags that are automatically placed before and after each line), I have the file that I need. The macro should generate several files so it is not pratically to do this manually for each file.
I have found following code to do the save-job :
strFileName = Application.ActiveWorkbook.Path & "\" & NameOfTheFile & ".xml"
Sheets(NameOfSheetContainingData).SaveAs Filename:=strFileName, FileFormat:=xlTextPrinter, CreateBackup:=False
This works perfectly, except for the UTF-8 formatting. Where I have a 'é' in excel, it turns in an 'xE9' in the xml-file.
I would be extreemly greatful I somebody could help me with this problem :)
Try
Sub SaveUTF8()
Const NameOfTheFile = "test"
Dim FSO, ts, ar, strFilename As String, s As String
Dim i As Long, t0 As Single: t0 = Timer
strFilename = ActiveWorkbook.Path & "\" & NameOfTheFile & ".xml"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set ts = FSO.createTextfile(strFilename, 1, 1) ' oversrite, utf8
ar = Sheets(1).UsedRange.Columns(1).Value2 'NameofSheetContainingData
For i = LBound(ar) To UBound(ar)
s = s & ar(i, 1) & vbCrLf
If i Mod 1000 = 0 Then
ts.write s
s = ""
End If
Next
ts.write s
ts.Close
MsgBox strFilename & " created in " & Int(Timer - t0) & " seconds"
End Sub
Alternative
Sub SaveUTF8_2()
Const NameOfTheFile = "test"
Dim strFilename As String, cell As Range
Dim t0 As Single: t0 = Timer
strFilename = ActiveWorkbook.Path & "\" & NameOfTheFile & ".xml"
Dim objStream
Set objStream = CreateObject("ADODB.Stream")
With objStream
.Type = 2 'adTypeText
.Open
.Charset = "UTF-8"
For Each cell In Sheets(1).UsedRange.Columns(1).Cells
.writetext cell.Value2, 1 'adWriteLine
Next
.Position = 0
.SaveToFile strFilename, 2 'adSaveCreateOverWrit
End With
objStream.Close
MsgBox strFilename & " created in " & Int(Timer - t0) & " seconds"
End Sub
Sub testdata()
Sheet1.Range("A1:A300000").Value2 = _
"<tag atr1=""attribute one"" atr2=""attribute two"">some text here ééé</tag>"
End Sub
update - batch write 1000 lines
update2 - added alternative

Add every file inside a folder

I'm trying to do a macro that let's the user select a folder with more folders inside, this folders could have images .jpg or .png. What I want is that the macro adds only the image files in the excel, any image file. What it does right now is that adds the images but only if they have for name 1.jpg, 2.jpg, 3.jpg and so on.
Dim Secfolder As String
MsgBox ("Busque y seleccione la carpeta que contiene las carpetas de los sectores en el punto que realizará.")
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Buscar carpeta"
.ButtonName = "Aceptar"
.InitialFileName = "C:\"
If .Show = -1 Then
Secfolder = .SelectedItems(1)
End If
Sheets("Matriz_de_Hallazgos").Select
l = 1
For i = 1 To 200
idm = (Worksheets("Matriz_de_Hallazgos").Cells(i + 2, 1))
If idm = 1 Then
Application.SpellingOptions.IgnoreCaps = True
' Colocar la ruta de las fotos; las fotos deben llamarse como números. Ej: 1.jpg'
RutaCompleta = Secfolder & "\" & "sector " & idm & "\" & l & ".jpg"
ActiveSheet.Cells(i + 2, 3).Select
With ActiveSheet.Shapes.AddPicture(Filename:=RutaCompleta, linktofile:=msoFalse, _
SaveWithDocument:=msoCTrue, Left:=0, Top:=0, Width:=0, Height:=0)
.LockAspectRatio = 0
.Top = ActiveCell.Top
.Left = ActiveCell.Left
.Width = ActiveCell.Width
.Height = ActiveCell.Height
End With
l = l + 1
End If
Next i
Any ideas? Thank you
It is adding 1.jpg,2.jpg etc. because you have used l variable in the following line.
RutaCompleta = Secfolder & "\" & "sector " & idm & "\" & l & ".jpg"
You will have to use actual file name instead of l variable.
You can use the following to loop through the files for the selected folder.
FolderName = "D:\" 'Replace it with selected folder
Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
Set FSOFolder = FSOLibrary.GetFolder(FolderName)
Set FSOFile = FSOFolder.Files
'Use For Each loop to loop through each file in the folder
For Each FSOFile In FSOFile
'Insert actions to be perfomed on each file
MsgBox FSOFile.Name
Next

Dynamic Update last non empty cell in a column VBA Excel

I'm trying to write in an Excel sheet with a VBA macro. After I open a workbook with:
Set wrk=open ("C:/text.xlsx")
I find last non empty cell in a column "B",
for example with:
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
then I write one with:
cell(LastRow,2) =1
but when I want to write in column "D" the same way:
LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
cell(lastRow,4)=1
the macro writes one in the same row as the first one, knowing that the last non empty cell in column "B" and column "D" are not the same.
I wrote:
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.AskToUpdateLinks = False
before opening the Excel sheet to make the macro faster.
Mycode:
Option Explicit
Private Sub maac() ' fonction de décharge de questionnaire type Compostage
Dim src_path, distination_Path As String
Dim source, distination As String 'workbooks
Dim src_feuil, via, distination_feuil As String 'sheets
Dim src_cell_address As String ' adresses
Dim count, countB, last_via_cell, distination_col_address As Integer
Dim last_dist_row As Long
Dim dist_path_fname As String
Dim co, wrk As Workbook
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.AskToUpdateLinks = False
'Desactive les alerts et les mises à jour écran
'App_prop.app_disable
Set co = ThisWorkbook
via = ActiveSheet.Name 'activated Via worksheet
last_via_cell = Sheets(via).UsedRange.Rows.count
'MsgBox ActiveSheet.Name ' nom de la feuil active
'MsgBox Sheets(via).Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
src_path = Sheets(via).Cells(2, 1).Value
source = "src.xlsx"
src_feuil = Sheets(via).Cells(2, 3).Value
src_cell_address = Sheets(via).Cells(Sheets(via).Cells(2, 6).Value, Sheets(via).Cells(2, 7).Value).Address
distination_Path = Sheets(via).Cells(2, 9) ' path of source file (questionnaire) bdd file path
distination = Sheets(via).Cells(2, 8) ' name of bdd file
distination_feuil = Sheets(via).Cells(2, 10) ' name of sheet of bdd file
distination_col_address = Sheets(via).Cells(2, 12)
'DoEvents
Set wrk = Workbooks.Open(distination_Path & "\" & distination & ".xlsx")
'Application.ScreenUpdating = False
last_dist_row = wrk.Sheets(distination_feuil).Cells(Rows.count, distination_col_address).End(xlUp).Row + 1
MsgBox last_dist_row
wrk.Sheets(distination_feuil).Cells(last_dist_row, distination_col_address) = GetValue(src_path, source, src_feuil, src_cell_address) 'GET VALUE
For count = 3 To last_via_cell
'---- SOURCE COORDINATIONS
'Workbooks("C:\Users\pc\Desktop\comp.xlsm").Sheets("Compostage").Activate
src_path = co.Sheets(via).Cells(count, 1) ' path of source file (questionnaire)
source = "src.xlsx" ' name of source file (questionnaire)
src_feuil = co.Sheets(via).Cells(count, 3) ' name of source file sheet (questionnaire)
src_cell_address = co.Sheets(via).Cells(co.Sheets(via).Cells(count, 6).Value, co.Sheets(via).Cells(count, 7).Value).Address
'----- BDD COORDINATIONS
distination_Path = co.Sheets(via).Cells(count, 9) ' path of source file (questionnaire) 'bdd file path
distination = co.Sheets(via).Cells(count, 8) ' name of bdd file
distination_feuil = co.Sheets(via).Cells(count, 10) ' name of sheet of bdd file
distination_col_address = co.Sheets(via).Cells(count, 12)
MsgBox "col" & distination_col_address
If co.Sheets(via).Cells(count, 8) <> co.Sheets(via).Cells(count - 1, 8) Then
wrk.Save
wrk.Close
Set wrk = Nothing
Set wrk = Workbooks.Open(distination_Path & "\" & distination & ".xlsx")
last_dist_row = wrk.Sheets(distination_feuil).Cells(Rows.count, distination_col_address).End(xlUp).Row + 1 ' get the last empty row in BDD
'MsgBox "row" & last_dist_row
wrk.Sheets(distination_feuil).Cells(last_dist_row, distination_col_address) = GetValue(src_path, source, src_feuil, src_cell_address) 'get value
Else
'--------------------------OPEN
'last_dist_row =wrk.Sheets(distination_feuil).Range("A1").End(xlDown).Row + 1 get the last empty row in BDD
last_dist_row = wrk.Sheets(distination_feuil).Cells(Rows.count, distination_col_address).End(xlUp).Row + 1
wrk.Sheets(distination_feuil).Cells(last_dist_row, distination_col_address) = GetValue(src_path, source, src_feuil, src_cell_address) 'GET VALUE
End If
Next count
wrk.Save
wrk.Close
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.AskToUpdateLinks = True
End Sub
Private Function GetValue(path, file, sheet, ref)
'Retrieves a value from a closed workbook
Dim arg As String
' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
' Execute an XLM macro
If ExecuteExcel4Macro(arg) = 0 Then
GetValue = ""
Else: GetValue = ExecuteExcel4Macro(arg)
End If
End Function

Resources