How to export from query/database table to cvs file - vba

Hi friends at Stackoverflow
Im trying to export a table to a cvs file but i get an error. I tried to troubleshoot but no success so far.
Private Sub cmdGenerateExcelFilesPM_Click()
On Error GoTo HandleError
Dim fullPath As String
fullPath = CurrentProject.path
Dim CaseNumber As String
CaseNumber = Forms("Form").Controls("txtCaseNum").Value
Dim query As String
query = "Select * from PromoAPI"
'this line works fine and generate an excel file
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "PromoAPI",
CurrentProject.path & "\" & CaseNumber & " Promo API" & Format(Now(), " mm dd yyyy"), True
'I need a CVS file - none of the below line works -all of them throw the same error
DoCmd.TransferText acExportDelim, , "PromoAPIQuery", CurrentProject.path & "\" &
CaseNumber &
" Promo API" & Format(Now(), " mm dd yyyy"), True
DoCmd.TransferText acExportDelim, , "query", CurrentProject.path & "\" & CaseNumber & "
Promo API" & Format(Now(), " mm dd yyyy"), True
DoCmd.TransferText acExportDelim, "", "PromoAPI", CurrentProject.path & "\" & CaseNumber & "
Promo API" & Format(Now(), " mm dd yyyy"), True
HandleExit:
Exit Sub
HandleError:
MsgBox Err.Description
Resume HandleExit
End Sub
I have my query named PromoAPIQuery
The error I keep getting is
If anyone can Point me in the right direction please I'd appreciate it.
Thank you

That is just a "bad" error message.
Your issue is you not supplied a file extension (csv) in this case.
Hence, this should work:
Dim strF As String
strF = CurrentProject.path & "\" & _
CaseNumber & " Promo API" & Format(Now(), " mm dd yyyy") & ".csv"
DoCmd.TransferText acExportDelim, , "PromoAPIQuery", strF, True
so note the "addition" of the ".csv" in above.

Related

Access OutPutTo to folder

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

Explanation on uploading files to share point using vba

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

Save a single worksheet as CSV/xlsx file error 1004 (but does work when use 'export as fixed format' for PDF)

I have managed to get this to save as a PDF using 'ExportAsFixedFormat', but when I try to use 'SaveAs' to get a CSV (although I would accept xlsx too!) I get:
Run time error: 1004 Application defined or Object defined error
I have spent way to long trying to do this and can't find any answers that work for me online...
Sub SaveTrackingSheet()
Dim NewPathTrack As String
NewPathTrack = Application.ThisWorkbook.Path & "\PDF Outputs\" & Range("NameTrack").Text & "\"
If Dir(NewPathTrack, 63) = "" Then MkDir NewPathTrack
Dim NewPathDealer As String
NewPathDealer = NewPathTrack & Range("CodeTrack").Text & " - " & Range("NameTrack").Text & "\"
If Dir(NewPathDealer, 63) = "" Then MkDir NewPathDealer
Sheets("Tracking Sheet").SaveAs _
Filename:=NewPathDealer & "\" & Range("CodeTrack").Text & " - Tracking Sheet" & ".csv", _
FileFormat:=xlCSV, _
ConflictResolution:=2, _
Local:=True, _
CreateBackup:=False
End Sub
This is the line that errors:
Sheets("Tracking Sheet").SaveAs _
Filename:=NewPathDealer & "\" & Range("DealerCodeTrack").Text & " - Tracking Sheet" & ".csv", _
FileFormat:=xlCSV, _
ConflictResolution:=2, _
Local:=True, _
CreateBackup:=False
Thanks in advance!
fileformat:=xlCSVMSDOS
Check fileformat specifications at https://msdn.microsoft.com/es-es/vba/excel-vba/articles/xlfileformat-enumeration-excel
UPDATED RIGHT NOW:
The code that works for me is:
Sub SaveTrackingSheet()
Dim NewPathTrack As String
NewPathTrack = Application.ThisWorkbook.Path & "\PDF Outputs\" & Range("NameTrack").Text & "\"
If Dir(NewPathTrack, 63) = "" Then MkDir NewPathTrack
Dim NewPathDealer As String
NewPathDealer = NewPathTrack & Range("CodeTrack").Text & " - " & Range("NameTrack").Text & "\"
If Dir(NewPathDealer, 63) = "" Then MkDir NewPathDealer
Sheets("Tracking Sheet").SaveAs _
Filename:=NewPathDealer & Range("CodeTrack").Text & " - Tracking Sheet" & ".csv", _
FileFormat:=xlCSV, _
Local:=True, _
CreateBackup:=False
'ConflictResolution:=2 This line causes the error
End Sub
Hope it helps!

vba saving word file to created folder

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

Script stops on protected files such as system files

This code stops after a while due to protected files such as system files, "Permission Denied".
Is there a way to modify the code below so that it can handle such protected files or bypass them?
Set objFS=CreateObject("Scripting.FileSystemObject")
WScript.Echo Chr(34) & "Full Path" &_
Chr(34) & "," & Chr(34) & "File Size" &_
Chr(34) & "," & Chr(34) & "File Date modified" &_
Chr(34) & "," & Chr(34) & "File Date Created" &_
Chr(34) & "," & Chr(34) & "File Date Accessed" & Chr(34)
Set objArgs = WScript.Arguments
strFolder = objArgs(0)
Set objFolder = objFS.GetFolder(strFolder)
Go (objFolder)
Sub Go(objDIR)
If objDIR <> "\System Volume Information" Then
For Each eFolder in objDIR.SubFolders
Go eFolder
Next
End If
For Each strFile In objDIR.Files
WScript.Echo Chr(34) & strFile.Path & Chr(34) & "," &_
Chr(34) & strFile.Size & Chr(34) & "," &_
Chr(34) & strFile.DateLastModified & Chr(34) & "," &_
Chr(34) & strFile.DateCreated & Chr(34) & "," &_
Chr(34) & strFile.DateLastAccessed & Chr(34)
Next
End Sub
Then call it from the command line
like this.
c:\test> cscript //nologo myscript.vbs "c:\" > "C:\test\Output.csv"
I've simplified your code (based upon your duplicate question) and without trying to handle errors I can see a problem: objDIR.SubFolders fails when one of the subfolders (such as \System Volume Information) doesn't have permissions to be viewed! You need to use another method on Folder to enumerate the foldernames, combine them with the existing path and then trap the error .GetFolder may cause when you don't have permissions. (I don't have time to code that solution at the moment.)
Option Explicit
Dim objFS
Dim objArgs
Dim strFolder
Dim objFolder
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
WScript.StdOut.WriteLine """Full Path"",""File Size""," & _
"""File Date modified"",""File Date Created""," & _
"""File Date Accessed"""
Set objArgs = WScript.Arguments
strFolder = objArgs(0)
Set objFolder = objFS.GetFolder(strFolder)
Go objFolder
Sub Go(objDIR)
Dim strFile
On Error Resume Next
For Each eFolder in objDIR.SubFolders
Go eFolder
Next
For Each strFile In objDIR.Files
WScript.StdOut.WriteLine """" & strFile.Path & """,""" & _
strFile.Size & """,""" & _
strFile.DateLastModified & """,""" & _
strFile.DateCreated & """,""" & _
strFile.DateLastAccessed & """"
Next
End Sub
VBScript allows error trapping, though not as gracefully as VBA. Try the script below.
On Error Resume Next
'[ ... code ... ]
Dim test_result, divisor
divisor = 1 '' No error
'divisor = 0 '' raise error #11
'divisor = "zero" '' raise a different error
test_result = 2/divisor
If Err.Number = 11 then ''This line must appear at the point error is raised
MsgBox "Handled Error: " & Err.Description
ElseIf Err.Number > 0 then
MsgBox "Error: " & Err.Number & " " & Err.Description
Err.Clear ''if you wanted to proceed clean from here
End If
MsgBox "Result: " & test_result
ensure the process has permissions. see
You can ignore script errors in VBScript by adding
On Error Resume Next
before the part of the code where you want to ignore errors.
The statement to restore the default behavior is
On Error GoTo 0
And just a remark: Method calls in VB and VBScript don't use parenthesis if they appear as a single statement. So the line Go (objFolder) should be replaced by Go objFolder.