Excel VBA, suddenly can't find path? - file

I got this:
"vba runtime error, cannot save the attachment. path does not exist. verify the path is correct"
I use this:
Sub Save_Outlook_Attachements_Calls()
Dim ol As Outlook.Application
Dim ns As Outlook.Namespace
Dim callfol As Outlook.Folder
Dim salefol As Outlook.Folder
Dim i As Object
Dim mi As Outlook.MailItem
Dim at As Outlook.Attachment
Dim fPat As String
fPat = ThisWorkbook.Path
Set ol = New Outlook.Application
Set ns = ol.GetNamespace("MAPI")
Set FSO = CreateObject("Scripting.FileSystemObject")
Set callfol = ns.Folders("xxx.xxx#xxx.com").Folders("OutlookData").Folders("Calls")
For Each i In callfol.Items
If i.Class = olMail Then
Set mi = i
If mi.Attachments.Count > 0 And Format(mi.ReceivedTime, "yyyy-mm-dd") = Format(Date, "yyyy-mm-dd") Then
For Each at In mi.Attachments
'------------ ------------
at.SaveAsFile (fPat & "\Outlookdata\calls\" & Date & "." & FSO.GetExtensionName(fPat & "\Outlookdata\calls\" & at.Filename))
Next at
End If
End If
Next i
End Sub
It's the Row in the end that gets the error message:
Starting with "at.SaveAsFile (fPat &"
I have checked what the variabel "Fpat" contains, and its "H:\VBA"
So its like it always has been, and the server still called H:
All of that has been working perfect, but suddenly it doesn't?
Its a server map, but i can reach it in the file explorer like normal.
I have restarted the pc :) but error persists.
Any suggestions?

I solved it, i had changed the windows system language to English last week, not just the programs, in which already is in english.
That made the date variable im using to the format 2022/06/20, ie: "/" and that cannot be used in a file name..
i never thought i would find it by my self :)

Related

Access VBA - method or data member not found error

I'm new to Access and thank you for reading this first.
I'm exporting a query in Access to a pipe delimited CSV file. The query is from a table which is ODBCed from SQL.
I've been getting for the line dbs.Recordset : Method or data member not found error.
Huge thanks for any suggestion to fix this.
Option Compare Database
Option Explicit
Sub Command12_Click()
Dim dbs As DAO.database
Dim rst As DAO.Recordset
Dim intFile As Integer
Dim strFilePath As String
Dim intCount As Integer
Dim strHold
strFilePath = "C:\temp\TEST.csv"
Set dbs = CurrentDb
Set rst = db.OpenRecordset("T_Export_CSV", dbOpenForwardOnly)
intFile = FreeFile
Open strFilePath For Output As #intFile
Do Until rst.EOF
For intCount = 0 To rst.Fields.Count - 1
strHold = strHold & rst(intCount).Value & "|"
Next
If Right(strHold, 1) = "|" Then
strHold = Left(strHold, Len(strHold) - 1)
End If
Print #intFile, strHold
rst.MoveNext
strHold = vbNullString
Loop
Close intFile
rst.Close
Set rst = Nothing
MsgBox ("Export Completed Successfully")
End Sub
Thank you so so much for your time and please leave any comment below for any clarification if needed. I will try my best to be responsive!
Office 15.0 object library is the one you need to include in the references for O365 objects or Office 2013 Access VBA

Getting an error (3163) on MS Access 2003

The error says "The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data."
The database is supposed to pull in information from the Excel sheet that is passed through to it, and import the information into a recordset of the text field. However, the text field, somewhere down the line, has been limited to 50 characters. How can I change the maximum size of the text field? Thank you for any help
This is just part of the code, and the textfield I'm trying to make larger is "Idea_#", which is the last line of the code i posted
Sub Read_Recommendations()
On Error GoTo error_code
Dim FD As Office.FileDialog
Dim xlapp As Excel.Application
Dim xlsheet As Excel.Worksheet
Dim xlbook As Excel.Workbook
Dim db As Database
Dim rs As Recordset
Dim sql As String
Dim WP As String
Dim row As Integer
Dim File As String
Set db = CurrentDb
Set FD = Application.FileDialog(msoFileDialogOpen)
If FD.Show = True Then
File = FD.SelectedItems(1)
Set xlapp = CreateObject("Excel.Application")
Set xlbook = GetObject(File)
Set xlsheet = xlbook.Worksheets("Recommendation Approval Form")
Dim protection As Boolean
With xlsheet
'support unprotected worksheets
protection = xlsheet.ProtectContents
If protection Then xlsheet.Unprotect "veproject"
WP = .Range("WP_Number")
' Check that active WP and the WP of the uploading form is the same
' If WPs are different, awares users and prompts user whether or not to continue
Dim DifferentProject As String
If Not get_WP = WP Then
DifferentProject = MsgBox("You are uploading to the project with WP number: " & WP & " which is not the active project. Do you wish to continue?", vbYesNo)
If DifferentProject = 7 Then Exit Sub
End If
' Check that WP is correct by checking if it exists in the Record Information table
' delete the existing recomendations, we want to keep the most recent recomendations
' perhaps change this to a dialog in the future
sql = "DELETE * from tbl_recomendations WHERE WP_Number = '" & WP & "'"
db.Execute (sql)
row = 8
Set rs = db.OpenRecordset("tbl_recomendations")
Do While .Range("D" & row) <> ""
rs.AddNew
rs("WP_Number") = WP
rs("Idea_#") = (.Range("C" & row))
........
In Access, open tbl_recomendations in Design View. It sounds like the Field Size property for Idea_# is set at 50. You can change that up to 255.
If you need to store more than 255 characters in Idea_#, change its Data Type from Text to Memo.

Invalid Qualifier for String.Add in Outlook VBA

You all have been so helpful, and I was wondering whether I might trouble you a bit more. I have nearly completed my conversion from VB.net to VBA for Outlook, and in order to complete that, I need some information on what exactly a particular piece of code is returning. If you all can help out with that, the problem may go away; if not, I might need some help on this invalid qualifier error.
From what I understand, I declare an 'array' in VBA with a command like this:
Dim Computers(1, 1) As String
Which produces a 2x2 array. I then try to fill it like this:
Computers.Add ComputerName, ErrorState
where ComputerName and ErrorState are variables which I have already filled. This results in the error. I will provide you with the entire relevant section below. I need to know how many relevant items are in the outlook inbox, which means checking if they were sent on today's date and by the correct sender. I need this in order to get the correct dimensions on the array Computers. (The array is filled in right now as I know the correct dimensions, but in practise I will not.) I took a piece of code which I found through google, the Scripting Dictionary output, but I do not fully understand it. I need just the number of emails, without any irrelevant text, and I was hoping that the debug line would be able to tell me which command I would need to return the number and nothing else. Unfortunately, because of the above error, I cannot get to this line. Even by stepping through the code, the very first thing it tells me is that there is a problem here. The entire relevant section is below. I know that the formatting is problematic, but I have only been working with VB.NET for 4 days, and this is my second day of working with VBA, so I do not quite have everything down yet. There's some irrelevant stuff in here, I'm pretty sure, but I do not have the experience to make the call of whether something is relevant or not, so I left it all. Sorry for the length!
Private Sub Main()
Dim objOutlook As Outlook.Application
Dim Inbox As Outlook.MAPIFolder
Dim InboxItems As Outlook.Items
Dim Mailobject As Object
Dim strDate As String
Dim ComputerName As Object
Dim ErrorState As Object
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim SenderEmail As String
Dim Computers(1, 1) As String
Dim compLength As Integer
Dim disabledList As Collection
Dim enabledList As Collection
Dim unknownList As Collection
Dim notpresentList As Collection
Dim problemList As Collection
Dim cArrayLength As Integer
Dim I As Integer
Dim J As Integer
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim EmailCount As Integer
Dim compArray() As String
'\\ load csv declarations
Dim file_name As String
Dim fnum As Integer
Dim whole_file As String
Dim lines As Variant
Dim one_line As Variant
Dim num_rows As Long
Dim num_cols As Long
Dim R As Long
Dim C As Long
Set disabledList = New Collection
Set enabledList = New Collection
Set unknownList = New Collection
Set notpresentList = New Collection
Set problemList = New Collection
'\\\\\
'\\Retrieve info from outlook, add to sorted list Computers
'\\\\\
objOutlook = CreateObject("Outlook.Application")
Inbox = objOutlook.GetNamespace("Mapi").GetDefaultFolder(6)
InboxItems = Inbox.Items
InboxItems.SetColumns ("SentOn")
Dim myItems As Outlook.Items
Dim dict As Object
Dim msg As String
Set dict = CreateObject("Scripting.Dictionary")
myItems.SetColumns ("SentOn")
EmailCount = InboxItems.Count
For Each Mailobject In InboxItems
strDate = GetDate(Mailobject.SentOn)
If Not dict.Exists(strDate) Then
dict(strDate) = 0
End If
dict(strDate) = CLng(dict(strDate)) + 1
Next Mailobject
'\\ need redo to assign number of objects to CompLength
msg = ""
For Each o In dict.Keys
msg = msg & o & ": " & dict(o) & " items" & vbCrLf
Next
Debug.Print msg
For Each Mailobject In InboxItems
ComputerName = Mailobject.Subject
ErrorState = Mailobject.Body
strDate = GetDate(Mailobject.SentOn)
SenderEmail = Mailobject.SenderEmailAddress
If strDate = DateToday And SenderEmail = "itadmin#email.org" Then
'\\ Syntax is (key, value)
Computers.Add ComputerName, ErrorState
End If
'MsgBox(Mailobject.Subject)
'MsgBox(Mailobject.SenderName)
'MsgBox(Mailobject.To)
'MsgBox(Mailobject.Body)
Next Mailobject
This website has been incredibly helpful as not only a place for me to ask questions but also as a place for me to find relevant information without having to trouble you all. Unfortunately, it is all too often that I do have to trouble you all, but every time you have been very kind and helpful. And I would like to thank you for that.
you're trying to use the Add() method from a Collection to assign an element in an array. To assign an element in a 2-D array you'd use arr(a,b)=someValue where a and b are numeric values. – Tim Williams
Question with no answers, but issue solved in the comments

while rs edit update not working as expected

I have put together a procedure to cycle through a table containing paths to text files and import them into the database.
Reason for procedure:
The reason for this is I am building a back end to many reporting databases that rely on nightly updated text files. Recently they changed the server name and file names for these files, so I'm trying to build something more reliable so I don't have to run through the link table wizard making sure all the data types are exactly the same as before.
Issue:
The issue I have is the With .edit .update isn't acting like I thought it should and updating the field 'Updated' in the table to today's date.
Here is the code. I'm still new to programming, so apologies.
Private Sub ImportAll()
' Loops through table containing paths to text files on network and imports
Dim ID As Integer
Dim netPath As String
Dim netDir As String
Dim netFile As String
Dim localTable As String
Dim activeTable As Boolean
Dim updatedTable As Date
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("Tables")
Do Until rst.EOF
ID = rst.Fields("Table ID").Value
netDir = rst.Fields("Network Location").Value
netFile = rst.Fields("File Name").Value
localTable = rst.Fields("Local Table Name").Value
activeTable = rst.Fields("Active").Value
updatedTable = rst.Fields("Updated").Value
If activeTable = True And updatedTable <> Date Then
If ifTableExists(localTable) Then
On Error GoTo ImportData_Err
CurrentDb.Execute "DELETE * FROM " & localTable, dbFailOnError
netPath = netDir & netFile
DoCmd.TransferText acImportDelim, , localTable, netPath, True, ""
rst.Edit
updatedTable = Date
rst.Update
Else
netPath = netDir & netFile
DoCmd.TransferText acImportDelim, , localTable, netPath, True, ""
With rs
.Edit
.Fields("Updated") = Date
.Update
End With
End If
End If
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
ImportData_Exit:
Exit Sub
ImportData_Err:
MsgBox Error$
Resume ImportData_Exit
End Sub
Thank you.
Where you have
With rs
You meant
With rst
Mistakes such as this can be caught by turning on Option Explicit. Option Explicit means that all variables must be declared.
See here: How do I force VBA/Access to require variables to be defined?

Outlook VB Macro - what am i doing wrong?

I am trying to send some files from a folder to a fixed email address, the files need to be sent in individual emails, the file names are random.
This topic got me started:
Send individual emails to predefined set of people with all files in a folder
I altered the code a tiny bit to suit my needs, but when I run the macro it isn't sending the files. I'm sure its a simple mistake but my knowledge is limited!
This is my code:
Option Explicit
Const SOURCE_FOLDER As String = "C:\Users\Me\Desktop\Test"
Const RECIP_A As String = "me#hotmail.com"
Const EMAIL_BODY As String = "Please find attached file. Thanks and Regards, ABC"
Sub SendPDFs()
On Error GoTo ErrorHandler
Dim fileName As String
fileName = Dir(SOURCE_FOLDER)
Do While Len(fileName) > 0
Call CreateEmail(SOURCE_FOLDER & fileName)
fileName = Dir
Loop
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
Function CreateEmail(fileName As String)
Dim olApp As Outlook.Application
Dim msg As Outlook.MailItem
' create email
Set olApp = Outlook.Application
Set msg = olApp.CreateItem(olMailItem)
' set properties
With msg
.Body = EMAIL_BODY
.Recipients.Add (RECIP_A)
.Attachments.Add fileName
.Send
End With
End Function
Ah! The only problem with the code is
Const SOURCE_FOLDER As String = "C:\Users\Me\Desktop\Test"
Change that to
Const SOURCE_FOLDER As String = "C:\Users\Me\Desktop\Test\"
Now try it. I tried and tested it and it works.
Also ensure that you have added reference to the Outlook object library.

Resources