vb.net,vba,api,delete , Removing Alert When Using DeleteFile API

Removing Alert When Using DeleteFile API


Tag: vb.net,vba,api,delete

I'm writing a VBA application which involves looping a large number of directories recursively. I am using the FindFirstFile API to to achieve this, as it offers a substantial performance boost over the FileSystemObject.

In order to remove the FSO from my code entirely, I need a routine to delete files. This has brought DeleteFile to my attention. Although I have it working - see the below code - it shows an alert to the users, asking if they'd like to delete the file. I need to remove this alert, as is possible with FSO. Application.DisplayAlerts = False does not work in this instance - most likely because it's an API call.

Is there a way to remove the alert?

    hWnd As Long
    wFunc As Long
    pFrom As String
    pTo As String
    fFlags As Integer
    fAborted As Boolean
    hNameMaps As Long
    sProgress As String
End Type

Private Const FO_DELETE = &H3

 Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long
 Private Declare Function DeleteFile Lib "kernel32" Alias "DeleteFileA" (ByVal lpFileName As String) As Long

Private Sub TestDelete()

With SHDirOp
    .wFunc = FO_DELETE
   '.pFrom is file to be deleted, copied, or moved should be
    .pFrom = "My Path Here"
   'you might also look at adding
End With

'struct (Type) is now properly initialized
'call the function
SHFileOperation SHDirOp

 End Sub


There are several SHFILEOPSTRUCT.fFlags options you'll want to consider. You are asking for FOF_NOCONFIRMATION, &H10. You probably want some more, like FOF_ALLOWUNDO, FOF_SILENT, FOF_NOERRORUI, it isn't clear from the question. Check the docs.


Retrieve full path of FTP file on drag & drop?

I can read the filename using next code when dragging a file from an Ftp folder browsed on Windows explorer. But is there a way to retrieve the full Ftp path? Private Sub DataGridView1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop Dim filename As String = "" If e.Data.GetDataPresent("UniformResourceLocator") Then...

VBA - Unable to pass value from Private to Public Sub

I have a tool which I am designing to present a number of questions to a user in a set of userforms. The form will generate a score via passing an integer result from the userform to a main sub, which passes the code to a worksheet. My problem is...

Comparing arrays with numbers in vb.net

I need a way to compare two arrays in vb.net and save result in third array: Dim KonRes(3) As Integer Dim UserRes(3) As Integer Dim YelRed(3) As Integer KonRes(0) = 1 KonRes(1) = 2 KonRes(2) = 3 KonRes(3) = 4 UserRes(0) = 4 UserRes(1) = 3 UserRes(2) = 2 UserRes(3)...

Can't output Guid Hashcode

I'm trying to use the hashcode of a guid as a random voucher name for a website, and have been trying to write new records to a SQL table with the Hashcode variable but it doesn't work. command.Parameters.Add("@voucherName", SqlDbType.NVarChar) command.Parameters("@voucherName").Value = Guid.NewGuid().GetHashCode() When using that code it just puts a...

Convert date to string format

I have successfully imported data from xls into dataGridView. The date column in dataGridView is showing the DateTime format. I want this date column to be displayed in "dd MMM yyyy" format. I have tried as shown below: connExcel.Open() Dim dtExcelSchema As DataTable dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing) Dim SheetName As...

Copying a Range from Excel and Pasting it into Powerpoint NOT as a metafile but as a table which you can edit in PPP

All I want to do is copy a range from Excel and then paste this range into PowerPoint. When my range is manually copied from Excel to the clipboard... If I right click on a blank slide when pasting into PowerPoint, it gives me the option to paste "using destination...

Using VLOOKUP formula or other function to compare two columns

I have one table like this: SHORT TERM BORROWING 1/6/2009 94304 12/31/2010 177823 6/30/2011 84188 12/31/2011 232144 6/30/2012 94467 9/30/2012 91445 12/31/2012 128523 3/31/2013 83731 6/30/2013 78330 9/30/2013 70936 12/31/2013 104020 3/31/2014 62345 6/30/2014 62167 9/30/2014 63494 12/31/2014 104239 3/31/2015 69056 I have another column which lists each date from...

Using date in CreateQueryDef

I have a table on which I run a query that I export to Excel. Here is an example: Table: Food Item | Price | Limit_Date | ------------------------------- Carrot | 0.80 | 08/07/2015 | Salmon | 4.30 | 01/07/2015 | Biscuits | 2.40 | 15/12/2015 | Milk | 1.00 |...

Creating a Range in VBA

I'm working on my first VBA function. The goal is to have a function that accepts two integers as inputs, and outputs an array containing all the integers in between the two inputs (end-points included). Example: If I input 5 and 9, the output should be an array of 5,...

Exit Sub And Call another Sub

I have two subs, sub1 and sub2. I want to exit sub1 completely and start sub2 if a condition is satisfied. My attempt is (running from : sub1 . . If x=y Then Exit Sub And Call sub2 End If . . End Sub ...

VB.Net DateTime conversion

I have a jquery datepicker in a usercontrol. On the usercontrol i have a property that will return the selected date to the page which contains my usercontrol. I try to convert the string to a date: Dim MyDate As System.DateTime = System.Convert.ToDateTime(txtFromDateF.Value, System.Globalization.DateTimeFormatInfo.InvariantInfo) i keep getting the error: String...

Visual Basic Datagrid View change row colour

Every other change to the datagrid view works fine but for some reason the row color just wont change. Ive debugged and my application goes through the loop to change the row color. Also I have a button that gives the datagrid view a new list and colors the rows...

Userform is not unloading once command button is pressed

Having a little trouble with my userform, its not unloading once i hit the command button the data is inputted to the sheet but the userform is not refreshed and the data stays in the text boxes. It was working fine until i put the data validation in, but i...

Converting ADODB Loop into DAO

Hi I've been developing a vba project with a lot of help from examples here. I'm trying to access a MS Access database from Excel VBA and import large data sets (500-100+ rows) per request. Currently, the following loop works using ADODB however, the Range("").Copyfromrecordset line is taking very long...

If cell value starts with a specific set of numbers, replace data

My cell values are strings of numbers (always greater than 5 numbers in a cell, ie 67391853214, etc.) If a cell starts with three specific numbers (ie 673 in a cell value 67391853214) I want the data in the cell to be replaced with a different value (if 673 are...

ZipEntry() and converting persian filenames

In my vb.net project I'm trying to add a file with a Persian name to a zip file and I do this with the code bellow: Dim myentry As New ZipEntry(dr.Item("MyFile").ToString()) zipOut.PutNextEntry(myentry) however when I open the zip file I see the file name is changed to a gibberish Is...

Get XML node value when previous node value conditions are true (without looping)

Sample XML - <?xml version="1.0"?> <Root> <PhoneType dataType="string"> <Value>CELL</Value> </PhoneType> <PhonePrimaryYn dataType="string"> <Value>Y</Value> </PhonePrimaryYn> <PhoneNumber dataType="string"> <Value>555-555-5554</Value> </PhoneNumber> <PhonePrimaryYn dataType="string"> <Value>Y</Value> </PhonePrimaryYn> <PhoneType dataType="string"> <Value>HOME</Value> </PhoneType>...

Copying sheet to last row of a sheet from another workbook

I'm stuck in this block of code that copies sheet("Newly Distributed") to the last row of sheet("Source") from another workbook. The error is runtime error 9. What's wrong with my code? Any response would be appreciated. Private Sub copylog3() Dim lRow As Long Dim NextRow As Long, a As Long...

Excel-VBA: create named Range in row until end of cell content

Imagine an Excel sheet with some rows and some content in each row (i.e. different column-length for each row). In Excel-VBA: How can I create a range-X within column-X that goes from row-cell-2 to the end of the content of this X-column ?? i.e. I would like to create a...

How do I do to count rows in a sheets with filters? With a suppress lines

I have a sheet with lots of columns, but when I filter and use count = Application.WorksheetFunction.CountA(Range("A:A")) It returns all the rows non Empty. Not only the rows I filtered....

Connecting to database using Windows Athentication

I would like to use window authentication in my program to connect to my sql server. users already have certain permissions on the SQL server and I would like to leverage that in my program. The way I currently connect to the server is using this connection string. Dim ConnectionString...

Get List of Elements in Tree with specific Field Value

I have an Interface like this: Public Interface TreeSelectorAttributes Property selectedInTreeSelector As Boolean Property Name As String ReadOnly Property childs As IEnumerable(Of TreeSelectorAttributes) End Interface and I have a TreeView which has a List of this TreeSelectorAttributes: Public Property rootList As IEnumerable(Of TreeSelectorAttributes) now after the User chooses which elements...

EXCEL VBA: How to manupulate next cell's (same row) value if cell.value=“WORD” in a range

I want to change the next cell in same row in a if cell.value="word" in a range. I have defined the range, using 'for' loop. In my code, if cell.value="FOUND THE CELL" then cell.value+1="changed the next right side cell" cell.value+2="changed the second right side cell" end if I know this...

Excel VBA Program Code by Using Randomize Timer

What is wrong in below program code, why not returning correct result. Whenever i put any number in excel cell (1,1) and run the program, Numbers changed automatically, also not throwing a correct result in cell (1,2). Please Help as i learning VBA. Private Sub Sheet2_1() Dim num1 As Integer...

excel search engine using vba and filters?

I am using the following vba code to filter my rows in excel based on the value in my cell C5 Sub DateFilter() 'hide dialogs Application.ScreenUpdating = False 'filter for records that have June 11, 2012 in column 3 ActiveSheet.Range("C10:AS30").AutoFilter Field:=1, Criteria1:="*" & ActiveSheet.Range("C5").Value & "*" Application.ScreenUpdating = True End...

Excel VBA User-Defined Function: Get Cell in Sheet Function was Called In

I have a user-defined function in Excel that I run in multiple sheets. I am trying to use Cells(i, j) to pull the value of cells by their row and column in the sheet in which my function is called. Instead, Cells(i, j) pulls the value of cell [i,j] in...

Extract All Named Ranges Into A Class

I have a workbook with a very large amount of named ranges (well over 200). I really need a way to work quickly and easily with all of the named ranges so I can then work with / populate them using VBA. My solution up until now has been to...

Custom drawing using System.Windows.Forms.BorderStyle?

I want to mimick drawing of default border based on value of property BorderStyle. Instead of single border around the control, my control is visualised as four adjacent custom-drawn boxes (2×2), each having standard border drawn individually. So for example, if Control.Border is set to FixedSingle value I want to...

Removing Alert When Using DeleteFile API

I'm writing a VBA application which involves looping a large number of directories recursively. I am using the FindFirstFile API to to achieve this, as it offers a substantial performance boost over the FileSystemObject. In order to remove the FSO from my code entirely, I need a routine to delete...

VBA how to initialize vCPath

How do I initialize vCPath? VBA Run-Time Error 1004 @Garry's Student says I "must somehow use the info you get from Application.FileDialog(msoFileDialogOpen) to generate the full filespec of the file you wish to open". What's the simplest way to do this? I am a VBA beginner: I have been programming...

Syntax error in Insert query in Mysql in VB.Net

I am doing project in VB.NET and backend is mysql Can you please tell me where the error is occured Public Sub ins() con.Open() Dim cmd1 As New OdbcCommand("insert into party values('" + pcode_txt.Text + "','" + Trim(UCase(name_txt.Text)) + "','" + Trim(UCase(addr_txt.Text)) + "','" + phone_txt.Text + "','" + combo_route.SelectedItem...

NullReference Error while assiging values of Modeltype in MVC View (Razor)

I have the following MVC Model: Public Class Employee Public Property EmployeeID As Integer End Class Controller: Namespace Controllers Public Class EmployeeController Inherits Controller Function Details() As ActionResult Dim employee As Employee employee = New Employee employee.EmployeeID = 101 Return View() End Function End Class End Namespace View: @ModelType MVCDemo.Employee...

Interface Controls for DoEvent in Excel

I have a macro to loop through a range and return emails to .Display based on the DoEvents element within my module. I iterate that: row_number = 1 'And Do DoEvents row_number = row_number +1 'Then a bunch of formatting requirements Loop Until row_number = 'some value I am wondering...

Gridview items not populating correctly

I have data I am trying to input into a gridview. I am looking up the number of rows for the gridview and adding data into them like this: My "test" however does not get populated into the Submitted and Variance BoundFields in the Gridview. All that populates is the...

How do I use VB.NET to send an email from an Outlook account?

I'm trying to send an email via an outlook email account through a vb.net program. When I run the code I get an error telling me that I don't have a secure connection. I've been searching online and have tried all the adjustments I've found but I'm still not having...

adding variables into another variable vba

Dim x As Long Dim y As Long Dim CDTotal As Double Dim CSTotal As Double Dim ETotal As Double Dim FTotal As Double Dim HTotal As Double Dim ITotal As Double Dim ITTotal As Double Dim MTotal As Double Dim TTotal As Double Dim UTotal As Double Dim TotalValue...

VBA data type to store Range().Characters()

I can't find a data type to store Characters from a Range. I already tried the following code, but nothing happened. I think the problem is because of wrong data type. Dim chars As Characters chars = Range("A2").Characters(0, 4) MsgBox chars.Text ...

How do you delete favorite folders in outlook using VBA

I wish to delete all the folders from the outlook favorites then subsequently replace them, but the delete doesn't seem to work. What's wrong with my code. Setup Objects works fine ' Get the "Favorite Folders" navigation group Set favGroup = Application.ActiveExplorer.NavigationPane.Modules.GetNavigationModule(olModuleMail).NavigationGroups.GetDefaultNavigationGroup(olFavoriteFoldersGroup) This works Set inboxFldr = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox) favGroup.NavigationFolders.Add (inboxFldr)...

Return index of word in string

This code: Module Module1 Sub Main() ' Our input string. Dim animals As String = "cat, dog, bird" ' See if dog is contained in the string. If Not animals.IndexOf("dog") = -1 Then Console.WriteLine(animals.IndexOf("dog")) End If End Sub End Module Return start position 5 in string But how to return...

Convert Double from String

When converting string to floating, the converter creates wrong results. ?Global.System.Convert.ToDouble("635705821821928755").ToString("0") "635705821821929000" ?Global.System.Convert.ToSingle("635705821821928755").ToString("0") "635705800000000000" I am working with VB.Net Visual Studio 2012, Framework 4 on ASP.Net Webpage. Is there any solution for converting huge numbers from string into floating?...

how can i use parameters to avoid sql attacks

I have a project without any parameters used in SQL queries. Is there any solution so that i don't have to change the function and validate parameters from the Query string itself? Query = "select * from tbl_Users where userName='"& textbox1.text &"' and password='"& textbox2.text &"' " ds = obj.ExecuteQueryReturnDS(Query)...

check if a list contains all the element in an array using linq

I have a list of objects and I have an array of keywords. I need to check if all the elements of the array are present inside the list of objects. The user enters the data to be searched like this pain+fever+thirst+itching My code looks like: //i check if the...

How to pass all value of ListBox Control to a function?

I am writing a simple application to read the value a textbox and add to a listbox control . But i have to pass the listbox control to function . Any suggestion ? Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load test("E:\Satyajit.txt") End Sub Public Function...

Filtering Last Duplicate Occurrence In A Datatable

I am sorting a datable with the following code.. Dim sortedExtRecords1 As DataTable sortedExtRecords1 = parsedDataset.Tables("Detail").Clone Dim dvParsedDataset1 As New DataView(parsedDataset.Tables("Detail")) dvParsedDataset1.Sort = AuthorizatonConstants.Authorization_ID sortedExtRecords1 = dvParsedDataset1.ToTable("Detail") I can further filter the results to only return non duplicates and if there is duplicates I want the last record of the...

Set Label From Thread

Form1.vb Imports System.Threading Public Class Form1 Dim demoThread As Thread Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim Start As New Class1 Me.demoThread = New Thread( _ New ThreadStart(AddressOf Start.ThreadProcSafe)) Me.demoThread.Start() End Sub Delegate Sub SetTextCallback([text] As String) Public Sub SetText(ByVal [text] As String) ' InvokeRequired required...

VBA “Compile Error: Statement invalid outside Type Block”

I am running a VBA Macro in Excel 2010 with tons of calculations, so data types are very important, to keep macro execution time as low as possible. My optimization idea is to let the user pick what data type all numbers will be declared as (while pointing out the...

I need help setting the RecordSource of a Report within a VBA Function

Ok, so I've been looking around here for a few days (and a few other sites) and while I have modified my code a good bit to find a solution, it still doesn't work. I have four source queries, and I'd like to set the record source of my report...

Activecell not in Array

Having difficulty comparing my activecell against a predefined array. After importing data from another source I want to trim out the columns I don't need I've trued the array as both undefined, string and variant And tried activecell / activecell.value <> NeededColumns No joy :( Sub Trim() Dim NeededColumns As...

Replace reference with its value in Excel VBA workbook

I have an Excel workbook to manage my Delivery Notes, which creates another workbook with actual delivery note and stores it in the folder for me, then places new record in my main workbook so that the Delivery Number for the next delivery note can be increased by 1. My...