Here is the code, please help! I'm so lost. It successfully goes through each ID in the database.txt but every time it throws the exception and reports cannot download. I'm at my wits end, I've tried changing this so many times but nothing. The idea here is to download a file based on the date and the user id.
If its not found - catch the exception, if it is found - print in the datagridview.
Loop until all the IDs have been read.
Dim myDate = Format(DateTimePicker2.Value, "yyyyMMdd")
Do Until DateTimePicker2.Value > DateTimePicker3.Value
For Each strID As String In System.IO.File.ReadAllLines("database.txt")
Try
My.Computer.Network.DownloadFile("ftp://user:pass#ftp.ftp.net/" & strID & "/" & myDate & ".txt", My.Application.Info.DirectoryPath & "\logs\" & strID & "\" & Format(DateTimePicker2.Value, "yyyyMMdd") & ".txt")
Catch nullDownload As System.Net.WebException
MsgBox("File " & strID & "\" & Format(DateTimePicker2.Value, "yyyyMMdd") & ".txt could not be downloaded")
End Try
If My.Computer.FileSystem.FileExists(My.Application.Info.DirectoryPath & "\logs\" & strID & "\" & Format(DateTimePicker2.Value, "yyyyMMdd") & ".txt") Then
For Each line As String In
System.IO.File.ReadAllLines(My.Application.Info.DirectoryPath & "\logs\" & strID & "\" & Format(DateTimePicker2.Value, "yyyyMMdd") & ".txt")
DataGridView1.Rows.Add(line.Split(","))
Next
End If
Next
DateTimePicker2.Value = DateTimePicker2.Value.AddDays(1)
Loop
If DateTimePicker2.Value > DateTimePicker3.Value Then
MsgBox("Download complete.")
End If
EDIT: Just wanted to clear some things up...this fails to download ANYTHING. Even if the file exists. I can pull the existing file using a separate function in my application so I know it works and I know the downloading code works. Something is just missing here...
Also for clarity the file address should be ftp://ftp.ftp.net/ID9999/20150718.txt
HUZZAH! It was the date. by using the date as a variable, it fails.
Instead of
My.Computer.Network.DownloadFile("ftp://user:pass#ftp.ftp.net/" & strID & "/" & myDate & ".txt", My.Application.Info.DirectoryPath & "\logs\" & strID & "\" & Format(DateTimePicker2.Value, "yyyyMMdd") & ".txt")
I use
My.Computer.Network.DownloadFile("ftp://user:pass#ftp.ftp.net/" & strID & "/" & Format(DateTimePicker2.Value, "yyyyMMdd") & ".txt", My.Application.Info.DirectoryPath & "\logs\" & strID & "\" & Format(DateTimePicker2.Value, "yyyyMMdd") & ".txt")
Related
I have been struggling to output the PDF report to the relevant folder within the server. The error which is showing is
RunTime error 3201, no record found.
Could you please help me to solve it?
Dim RFQNumber As String
Dim InNumber As String
Dim FullReportName As String
Dim path1 As String
RFQNumber = [Forms]![RFQ_Database]![RFQ_ExNumber]
InNumber = [Forms]![RFQ_Database]![RFQ_InNumber]
path1 = "\\AZBAK-FP02\Work\Old Server Data\V&C\" & RFQNumber & "\" & RFQNumber & " " & InNumber & ".pdf"
MsgBox (path1)
DoCmd.OutputTo acOutputReport, "AOrderFCAVienna", "PDFFormat(*.pdf)", path1, False
I believe the ampersand in the directory path is causing the issue.
ath1 = "\\AZBAK-FP02\Work\Old Server Data\V&C\" & RFQNumber & "\" & RFQNumber & " " & InNumber & ".pdf"
^^^
you may need to add chr code
ath1 = "\\AZBAK-FP02\Work\Old Server Data\V" & Chr(38) & "C\" & RFQNumber & "\" & RFQNumber & " " & InNumber & ".pdf"
Inserting a formula containing an ampersand into a cell
I am trying to upload files to a sharepoint site, and for some reason something weird happens, where the first file with never upload, but a random amount of files after that will upload, and then sometimes an error of 'Getting list of available content types and properties' appears.
So 2 things that i need some help with, firstly how do i make it so the first file will upload, and then why am i sometimes getting the content error
here is the code i am using
If Dir("\\server\content\90002613\Documents\TestGB\" & saveFileName, vbDirectory) = "" Then
MkDir ("\\server\content\90002613\Documents\TestGB\" & saveFileName)
End If
If Dir("\\server\content\90002613\Documents\TestGB\" & saveFileName & "\" & Format(lDate, "yyyy"), vbDirectory) = "" Then
MkDir ("\\server\content\90002613\Documents\TestGB\" & saveFileName & "\" & Format(lDate, "yyyy"))
End If
If Dir("\\server\content\90002613\Documents\TestGB\" & saveFileName & "\" & Format(lDate, "yyyy"), vbDirectory) <> "" Then
With ActiveWorkbook
Application.ActiveWorkbook.SaveAs Filename:="https://server/content/90002613/Documents/TestGB/" & saveFileName & "/" & Format(lDate, "yyyy") & "\GB RSM P" & Format(lDate, "mm") & "FY" & Format(lDate, "yyyy") & " " & saveFileName & ".xlsx"
Application.ActiveWorkbook.Close False
End With
End If
thank you
You should be able to save to the UNC path:
Const BASE_DIR As String = "\\server\content\90002613\Documents\TestGB\"
Dim dt
If Dir(BASE_DIR & saveFileName, vbDirectory) = "" Then
MkDir (BASE_DIR & saveFileName)
End If
dt = Format(lDate, "yyyy")
If Dir(BASE_DIR & saveFileName & "\" & dt, vbDirectory) = "" Then
MkDir (BASE_DIR & saveFileName & "\" & dt)
End If
With ActiveWorkbook
.SaveAs Filename:="BASE_DIR " & saveFileName & "\" & dt & _
"\GB RSM P" & Format(lDate, "mm") & "FY" & _
Format(lDate, "yyyy") & " " & saveFileName & ".xlsx"
.Close False
End With
I am trying to call a .bat file from VBA using: however I am getting Method Run of object IWshShell3 failed with the line in asteriks highlighted. I am not familiar with this error and don't know where to begin. I am running VB in excel 2010. Thank you :).
Dim PathCrnt As String
Dim wsh As Object
PathCrnt = ActiveWorkbook.Path & "\" & MyBarCode & "_" & MyScan
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
**wsh.Run "C:\Users\cmccabe\Desktop\NxClinical.bat", windowStyle, waitOnReturn**
End If
EDIT
The code runs but exits with error code 1. Basically, what I am trying to do is have the user enter a barcode and date, those values are used to change the directory to that. A batch file is called that runs a perl script on that directory. The batch file is not being called and I'm not sure why. Thank you :).
VBA
Private Sub CommandButton3_Click()
Dim MyBarCode As String ' Enter Barcode
Dim MyScan As String ' Enter ScanDate
Dim MyDirectory As String
MyBarCode = Application.InputBox("Please enter the barcode", "Bar Code", Type:=2)
If MyBarCode = "False" Then Exit Sub 'user canceled
Do
MyScan = Application.InputBox("Please enter scan date", "Scan Date", Date, Type:=2)
If MyScan = "False" Then Exit Sub 'user canceled
If IsDate(MyScan) Then Exit Do
MsgBox "Please enter a valid date format. ", vbExclamation, "Invalid Date Entry"
Loop
Range("B20").Value = MyBarCode
Range("B21").Value = CDate(MyScan)
MyDirectory = "N:\1_DATA\MicroArray\NexusData\" & MyBarCode & "_" & Format(CDate(MyScan), "m-d-yyyy") & "\"
' Create nexus directory and folder
If Dir(MyDirectory, vbDirectory) = "" Then MkDir MyDirectory
If MsgBox("The project file has been created. " & _
"Do you want to create a template for analysis now?", _
vbQuestion + vbYesNo) = vbYes Then
'Write to text file
Open MyDirectory & "sample_descriptor.txt" For Output As #1
Print #1, "Experiment Sample" & vbTab & "Control Sample" & vbTab & "Display Name" & vbTab & "Gender" & vbTab & "Control Gender" & vbTab & "Spikein" & vbTab & "SpikeIn Location" & vbTab & "Barcode"
Print #1, MyBarCode & "_532Block1.txt" & vbTab & MyBarCode & "_635Block1.txt" & vbTab & ActiveSheet.Range("B8").Value & " " & ActiveSheet.Range("B9").Value & vbTab & ActiveSheet.Range("B10").Value & vbTab & ActiveSheet.Range("B5").Value & vbTab & ActiveSheet.Range("B11").Value & vbTab & ActiveSheet.Range("B12").Value & vbTab & ActiveSheet.Range("B20").Value
Print #1, MyBarCode & "_532Block2.txt" & vbTab & MyBarCode & "_635Block2.txt" & vbTab & ActiveSheet.Range("C8").Value & " " & ActiveSheet.Range("C9").Value & vbTab & ActiveSheet.Range("C10").Value & vbTab & ActiveSheet.Range("C5").Value & vbTab & ActiveSheet.Range("C11").Value & vbTab & ActiveSheet.Range("C12").Value & vbTab & ActiveSheet.Range("B20").Value
Print #1, MyBarCode & "_532Block3.txt" & vbTab & MyBarCode & "_635Block3.txt" & vbTab & ActiveSheet.Range("D8").Value & " " & ActiveSheet.Range("D9").Value & vbTab & ActiveSheet.Range("D10").Value & vbTab & ActiveSheet.Range("D5").Value & vbTab & ActiveSheet.Range("D11").Value & vbTab & ActiveSheet.Range("D12").Value & vbTab & ActiveSheet.Range("B20").Value
Print #1, MyBarCode & "_532Block4.txt" & vbTab & MyBarCode & "_635Block4.txt" & vbTab & ActiveSheet.Range("E8").Value & " " & ActiveSheet.Range("E9").Value & vbTab & ActiveSheet.Range("E10").Value & vbTab & ActiveSheet.Range("E5").Value & vbTab & ActiveSheet.Range("E11").Value & vbTab & ActiveSheet.Range("E12").Value & vbTab & ActiveSheet.Range("B20").Value
Close #1
'Run ImaGene
If MsgBox("Please run the ImaGene analysis. " & _
"and click yes after it completes to verify the spike-ins.", _
vbQuestion + vbYesNo) = vbYes Then
'Update folder structure and call perl
Dim PathCrnt As String
Dim Wsh As Object
Dim WaitOnReturn As Boolean
Dim WindowStyle As Integer
PathCrnt = MyDirectory
Set Wsh = VBA.CreateObject("WScript.Shell")
WaitOnReturn = True
WindowStyle = 1
Wsh.Run PathCrnt & "C:\Users\cmccabe\Desktop\NxClinical.bat", WindowStyle, WaitOnReturn
End If
Else
MsgBox "Nothing has been done. ", vbExclamation, "Goodbye!"
End If
Application.DisplayAlerts = False
Application.Quit
End Sub
Dim PathCrnt As String
Dim wsh As Object
PathCrnt = ActiveWorkbook.Path & "\" & MyBarCode & "_" & MyScan
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errrCode As Long
errrCode = wsh.Run( "cmd /C ""C:\Users\cmccabe\Desktop\NxClinical.bat""" _
, windowStyle, waitOnReturn)
If errrCode = 0 Then
MsgBox "Done! No error to report."
Else
MsgBox "Program exited with error code " & errrCode & "."
End If
Note
explicitly run cmd /c;
enclose batch script (fully qualified) name in double quotes;
get (and treat) errrCode from called batch script.
If your batch script requires paramer(s), use them as follows (an example):
errrCode = wsh.Run( "cmd /C ""C:\Users\cmccabe\Desktop\NxClinical.bat"" par1 ""par 2""" _
, windowStyle, waitOnReturn)
Another example:
errrCode = wsh.Run( "cmd /C ""C:\Users\cmccabe\Desktop\NxClinical.bat"" " _
_ & """" & PathCrnt & """" , windowStyle, waitOnReturn)
I have tried a lot of different things, and it seems like I cannot get it to work. So basically, this is a small piece of my complete code.
I am using Microsoft Scripting Runtime to save the file, using the FileExists() to check if the file actually exist before saving.
This is working fine if I remove the IF-statement/Loop.
However, now it feels like FileExists won´t find the string, MyFilePath, when I run it with the IF/Loop. (getdirsubparentpath is a function)
Dim week, UserName As String
Dim MyFile, MyFilePath As String
Dim version As Integer
' Current week, XX
week = Format(Date, "ww")
' Username, e.g. niclas.madsen
UserName = Environ$("UserName")
' Initials, first letter of last and surname to caps
' e.g. niclas.madsen would be NM
UserName = UCase(Left(UserName, 1) & Mid(UserName, InStr(UserName, ".") + 1, 1))
' fix filename for saving purpose
MyFile = Replace(Replace("SupplierOrganization_W", "", ""), ".", "_") _
& "" _
& week _
& " " _
& UserName _
& ".csv"
'SupplierOrganization_WXX NM
MyFilePath = getDirSubParentPath & MyFile
' Look for the MyFilePath, if it exists then
' Add "-1" after the week number, if 1 exists, add 2, etc.
If Len(Dir(MyFilePath)) <> 0 Then
version = 0
Do
version = version + 1
MyFilePath = Dir(getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv")
Loop Until Len(Dir(MyFilePath)) < 0
End If
Dim tmpFile, tmpFilePath As String
tmpFile = getDirSubParentPath & "tmp_file.txt"
Dim tmpString As String
'Dim fso As New FileSystemObject
Dim fso As Object 'scripting.filesystemobject
Set fso = CreateObject("scripting.filesystemobject")
If fso.FileExists(MyFilePath) = True Then
Application.ScreenUpdating = False
Open MyFilePath For Input As #1
Open tmpFile For Output As #2
tmpString = Input(LOF(1), 1) 'read the entire file
tmpString = Replace(tmpString, (Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34)), "") 'eliminate double quotation and commas in the first line with UTF-8
Print #2, tmpString 'output result
Close #1
Close #2
fso.DeleteFile (MyFilePath) 'delete original file
fso.CopyFile tmpFile, MyFilePath, True 'rename temp file
fso.DeleteFile (tmpFile) 'delete temp file
Application.ScreenUpdating = True
MsgBox "Finished processing file", vbInformation, "Done!"
Else
MsgBox "Cannot locate the file : " & MyFilePath, vbCritical, "Error"
End If
Set fso = Nothing
End Sub
' Get Parent Sub Directory Path
Function getDirSubParentPath()
getDirSubParentPath = ThisWorkbook.Path & Application.PathSeparator & "CSV" & Application.PathSeparator & "Parent" & Application.PathSeparator
End Function
I finally manage to create a solution that seems viable. However, the code could use some cleaning up :) But it gets the job done.
So basically, I am having some issues with the loop. It will return a file named W16-0 (which should actual just be W16). It should only add the "-X" if W16 is found. So the incremental order should be W16, W16-1, W16-2, etc.
What I am doing is that I try to locate if there is a W16-0 and then replace it with W16. Furthermore, it seems like the loop will give me one higher than the amount of files I have. So that is where I also got an error. So if I had a W16-4, it would ask the macro to find and open a file named W16-5, which would obviously not exist.
If somebody could help me clean up the code, I would be really thankful!
Sub RemoveCommasDoubleQ()
'
' Enable a reference to 'Microsft Scripting Runtime'
' under VBA menu option Tools > References
Dim week, UserName As String
Dim MyFile, MyFilePath As String
Dim version As Integer
Dim fso As Object 'scripting.filesystemobject
Set fso = CreateObject("scripting.filesystemobject")
' Current week, XX
week = Format(Date, "ww")
' Username, e.g. niclas.madsen
UserName = Environ$("UserName")
' Initials, first letter of last and surname to caps
' e.g. niclas.madsen would be NM
UserName = UCase(Left(UserName, 1) & Mid(UserName, InStr(UserName, ".") + 1, 1))
' fix filename for saving purpose
MyFile = Replace(Replace("SupplierOrganization_W", "", ""), ".", "_") _
& "" _
& week _
& " " _
& UserName _
& ".csv"
'SupplierOrganization_WXX NM
'MyFilePath = ThisWorkbook.Path & "\CSV\Parent\" & MyFile
MyFilePath = getDirSubParentPath & MyFile
Debug.Print MyFilePath
Debug.Print "BEFORE LOOP"
'version = 1
Do While Len(Dir(MyFilePath)) <> 0
'// If it does, then append a _000 to the name
'// Change _000 to suit your requirement
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
'// Increment the counter
version = version + 1
'// and go around again
If MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-0" & " " & UserName & ".csv" Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & " " & UserName & ".csv"
Debug.Print MyFilePath
Debug.Print "IF LOOP"
End If
Loop
Debug.Print MyFilePath
Debug.Print "LOOP"
If fso.FileExists(getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv") = False Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version - 2 & " " & UserName & ".csv"
MsgBox getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
End If
fileName = fso.GetFileName(MyFilePath)
Debug.Print fileName
If MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-0" & " " & UserName & ".csv" Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & " " & UserName & ".csv"
Debug.Print MyFilePath
Debug.Print "her it should be 0"
End If
If MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & " " & UserName & ".csv" Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
End If
Debug.Print "HER ER VI"
fileName = fso.GetFileName(MyFilePath)
Debug.Print fileName
Dim tmpFile, tmpFilePath As String
tmpFile = getDirSubParentPath & "tmp_file.txt"
Dim tmpString As String
Debug.Print "------"
Debug.Print MyFilePath
If fso.FileExists(getDirSubParentPath & "SupplierOrganization_W" & week & "-0" & " " & UserName & ".csv") = True Then
MsgBox "Found the W-0"
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & " " & UserName & ".csv"
End If
Debug.Print "Found 0?"
Debug.Print MyFilePath
If fso.FileExists(MyFilePath) = True Then
Application.ScreenUpdating = False
Open MyFilePath For Input As #1
Open tmpFile For Output As #2
tmpString = Input(LOF(1), 1) 'read the entire file
tmpString = Replace(tmpString, (Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34)), "") 'eliminate double quotation and commas in the first line with UTF-8
Print #2, tmpString 'output result
Close #1
Close #2
fso.DeleteFile (MyFilePath) 'delete original file
fso.CopyFile tmpFile, MyFilePath, True 'rename temp file
fso.DeleteFile (tmpFile) 'delete temp file
Application.ScreenUpdating = True
MsgBox "Finished processing file", vbInformation, "Done!"
Else
MsgBox "Cannot locate the file : " & MyFile, vbCritical, "Error"
End If
Set fso = Nothing
End Sub
I have written the code below, currently it creates a folder. However I would like to save the same word doc to that folder. Any pointers on where I am going wrong??
Thanks
Sub newfold()
Dim strNewFolderName As String
strNewFolderName = "New Folder " & (Month(Now())) & " " & Year(Now)
If Len(Dir("c:\Users\Jabaar\Documents\" & strNewFolderName, vbDirectory)) = 0 Then
MkDir ("c:\Users\Jabaar\Documents\" & strNewFolderName)
End If
Dim PathName As String
PathName = ("New Folder " & MonthName(Month(Now())) & " " & Year(Now))
ActiveDocument.SaveAs "c:\Users\Jabaar\Documents\" & "(strNewFolderName)" + ".doc"
End Sub
Just replace
ActiveDocument.SaveAs "c:\Users\Jabaar\Documents\" & "(strNewFolderName)" + ".doc"
with
ActiveDocument.SaveAs FileName:="c:\Users\Jabaar\Documents\" & strNewFolderName & "\" & Split(ActiveDocument.Name, ".")(0) & ".doc", _
FileFormat:=wdFormatDocument
where Split(ActiveDocument.Name, ".")(0) takes current name of file without extension. You could replace it with desired name:
ActiveDocument.SaveAs FileName:="c:\Users\Jabaar\Documents\" & strNewFolderName & "\" & "newFile.doc", _
FileFormat:=wdFormatDocument
This is what have done and it seems work.
ActiveDocument.SaveAs "c:\Users\Jabaar\Documents\" & strNewFolderName & "\" & "test" + ".doc
The solution #simoco provided is what I was looking for, so thanks for confirming the formatting of it #simoco