excel vba open all files in folder and then iterate over files, get values from specified range and paste value to third line of file with the same index, then save file
Assistant
Certainly! Below is a VBA macro that:
Opens all Excel files in a specified folder,
For each file, reads values from a specified range (e.g., A1:C1),
Pastes those values into the third row of the same file, starting at row 3 and in the same columns,
Saves and closes each file.
vba
Sub ProcessFilesInFolder()
Dim folderPath As String
Dim fileName As String
Dim wb As Workbook
Dim sourceRange As Range
Dim pasteRow As Long
Dim fileIndex As Long
' Specify folder path (make sure it ends with a backslash "\")
folderPath = "C:\YourFolderPath\"
' Initialize file index
fileIndex = 1
' Get first file with .xls or .xlsx extension; modify as needed (you can add *.xls*, *.xlsm too)
fileName = Dir(folderPath & "*.xls*")
Do While fileName <> ""
' Open workbook
Set wb = Workbooks.Open(folderPath & fileName)
' Define the source range to copy from. Example: first row, A1:C1
Set sourceRange = wb.Sheets(1).Range("A1:C1")
' Define the paste row
pasteRow = 3 ' Third row
' Paste values into the third line of the worksheet (same columns as sourceRange)
sourceRange.Copy
With wb.Sheets(1).Rows(pasteRow)
.Cells(1, sourceRange.Column).PasteSpecial Paste:=xlPasteValues
End With
' Alternatively, without Copy/Paste, just assign values:
' wb.Sheets(1).Range(wb.Sheets(1).Cells(pasteRow, sourceRange.Column), wb.Sheets(1).Cells(pasteRow, sourceRange.Column + sourceRange.Columns.Count - 1)).Value = sourceRange.Value
' Save and close the workbook
wb.Close SaveChanges:=True
' Move to next file
fileName = Dir()
fileIndex = fileIndex + 1
Loop
MsgBox "Finished processing all files in folder.", vbInformation
End Sub
How to use:
Open Excel and press Alt + F11 to open the VBA editor.
Insert a new module (Insert > Module).
Paste the above code into the module.
Change folderPath to your target folder path where your Excel files are located.
Adjust sourceRange if you need a different range.
Run the macro (F5 or from Excel).
Notes:
This code processes all .xls and .xlsx files in the folder.
It assumes the data is in the first sheet (Sheets(1)). Adjust if you need a different sheet.
It copies values only (using .PasteSpecial Paste:=xlPasteValues).
No error handling is included; you may want to add error management if files might be corrupt, password protected, etc.
If you want me to customize the range, sheet name, or any other specific logic, just let me know!
User
excel vba open all txt files in folder and then iterate over files, get values from specified range and paste value to third line of file with the same index, then save file
Assistant
Thanks for clarifying you want to work with TXT files, not Excel files.
Since TXT files aren't Excel workbooks, VBA cannot open them as workbooks directly but you can:
Open each TXT file as a plain text file,
Read its content,
Get values from a specified range of lines or parts,
Modify the third line by inserting or replacing values,
Save changes back to the TXT file.
Let's clarify your requirements before proceeding:
What do you mean by "get values from specified range" in a TXT file?
For example, are you extracting some lines or part of lines from the TXT files?
When you say "paste value to third line of file with the same index", do you mean replace or insert data into the third line?
Or do you want to extract data from an Excel source to paste into TXT files? Or extract from TXT files themselves?
Based on the general case:
Script to:
Open all TXT files in a folder,
Read their entire content into an array of lines,
Modify the third line (line index 2) by replacing or appending something,
Save the file back.
Example VBA code to modify the third line of all TXT files in a folder:
vba
User
auto double click
Assistant
When you say "auto double click" — this can mean a few things depending on context:
Automatically simulate a double-click on a UI element (button, cell, file) programmatically.
Automate a double-click event inside Excel VBA.
Use Windows API to simulate mouse double-click at a screen position.
If you want to simulate a double-click on a cell in Excel VBA (e.g., automatically trigger code that normally happens on double-click):
You cannot literally "auto double click" a cell with VBA, but you can call the Worksheet_BeforeDoubleClick event procedure manually, or you can write a routine that performs the actions that normally happen in double-click.
Example: Trigger the Worksheet_BeforeDoubleClick event manually
vba
Sub SimulateDoubleClick()
' Call the double-click event handler on a specific cell.
Call Sheet1.Worksheet_BeforeDoubleClick(Range("A1"), Cancel:=False)
End Sub
Make sure your Worksheet_BeforeDoubleClick event procedure is in the correct sheet module (Sheet1 or whichever your sheet is):
vba
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Me.Range("A1")) Is Nothing Then
MsgBox "Cell A1 was double-clicked!"
Cancel = True
End If
End Sub
If you want to simulate an actual mouse double click at a screen coordinate using VBA + Windows API:
The code below uses mouse_event Windows API calls.
vba
User
autoit double click
Assistant
If you're asking how to simulate an auto double-click using AutoIt, AutoIt makes this kind of mouse automation very straightforward.
Basic AutoIt Double Click
AutoIt has a built-in function called MouseClick which can simulate mouse button clicks, including double-click.
Full small example: Copy selected text, read clipboard, then display message
autoit
; Copy selected text
Send("^c")
Sleep(200) ; give some time for clipboard to update
; Get copied text
Local $text = ClipGet()
MsgBox(0, "Copied Text", $text)
Summary
Use Send("^c") to simulate Copy keyboard shortcut.
Use ClipGet() and ClipPut() for clipboard manipulation.
Use FileCopy() to copy files.
If you meant something different by "autoit copy" or want a specific copy-related script, please provide more info!
User
select text with mouse move autoit
Assistant
To select text by simulating mouse movement and dragging (click + drag) using AutoIt, you basically:
Move the mouse to the start position
Hold down the left mouse button (click down)
Move the mouse to the end position (drag)
Release the mouse button
Basic AutoIt Script to Select Text by Mouse Drag
autoit
; Coordinates for start and end points (example values)
Local $startX = 300, $startY = 300
Local $endX = 600, $endY = 300
; Move mouse to start position
MouseMove($startX, $startY, 10) ; 10 = speed (1-100)
; Hold left mouse button down to start selection
MouseDown("left")
; Drag mouse to the end position to select text
MouseMove($endX, $endY, 10)
; Release mouse button to finish selection
MouseUp("left")
Explanation:
MouseMove(x, y, speed) — moves mouse cursor smoothly to the given screen coords.
MouseDown("left") — holds the left mouse button down (starts drag).
MouseUp("left") — releases the left mouse button (finishes drag).
Complete example with small delay:
autoit
; Wait before starting
Sleep(1000)
Local $startX = 300, $startY = 300
Local $endX = 600, $endY = 300
; Move cursor to start
MouseMove($startX, $startY, 10)
Sleep(100)
; Press left mouse button down
MouseDown("left")
Sleep(100)
; Drag to end position
MouseMove($endX, $endY, 10)
Sleep(100)
; Release left mouse button
MouseUp("left")
Notes:
Adjust $startX, $startY, $endX, $endY to match the screen coordinates of the text you want to select.
If you want vertical selection, change the Y coordinates.
If you want to select multiple lines, drag vertically.
Adding short Sleep() calls helps prevent the script from running too fast and missing some steps.
Let me know if you want a script that also copies the selected text or interacts with a specific window/control!
Sub ModifyThirdLineInTxtFiles()
Dim folderPath As String
Dim fileName As String
Dim fullPath As String
Dim fileContent() As String
Dim fileNum As Integer
Dim lineCount As Long
Dim i As Long
' Folder containing TXT files (with trailing backslash)
folderPath = "C:\YourFolderPath\"
' Get first txt file
fileName = Dir(folderPath & "*.txt")
Do While fileName <> ""
fullPath = folderPath & fileName
' Open file for reading to count lines
fileNum = FreeFile
Open fullPath For Input As #fileNum
' Read all lines into array using dynamic array
Dim tempLines() As String
ReDim tempLines(0)
i = 0
Do While Not EOF(fileNum)
ReDim Preserve tempLines(i)
Line Input #fileNum, tempLines(i)
i = i + 1
Loop
Close #fileNum
lineCount = i
' Check if file has at least 3 lines
If lineCount >= 3 Then
' Modify third line (index 2)
' Example: Replace third line with "This is the new third line for file index " & i
' Or you can read a value from somewhere else and insert here.
tempLines(2) = "This is the new third line for file: " & fileName
' To append instead of replace:
' tempLines(2) = tempLines(2) & " - Appended text"
Else
' If less than 3 lines, maybe add lines to reach third line
ReDim Preserve tempLines(2)
tempLines(2) = "This is the new third line for file: " & fileName
End If
' Open file for writing to overwrite content
fileNum = FreeFile
Open fullPath For Output As #fileNum
For i = 0 To UBound(tempLines)
Print #fileNum, tempLines(i)
Next i
Close #fileNum
' Next file
fileName = Dir()
Loop
MsgBox "Processed all TXT files.", vbInformation
End Sub
How this works:
You define your folder path (adjust "C:\YourFolderPath\").
Each TXT file is read line-by-line into a dynamic array.
The third line (line index 2) is replaced with an example string including filename.
If file has fewer than 3 lines, it expands the array and adds that third line.
The file is overwritten with the updated contents.
Moves on to next TXT file.
Customization options:
Instead of hardcoding the new third line, you can:
Read data from a separate Excel worksheet,
Extract specific parts from that TXT file,
Or apply any needed logic.
Please let me know if:
You want the new third line to be dynamically pulled from somewhere else,
Or if you want to extract a particular range from TXT content,
Or other specifics!
Happy to help you tailor this!
Private Declare PtrSafe Sub mouse_event Lib "user32" ( _
ByVal dwFlags As Long, _
ByVal dx As Long, _
ByVal dy As Long, _
ByVal cButtons As Long, _
ByVal dwExtraInfo As Long)
Const MOUSEEVENTF_LEFTDOWN = &H2
Const MOUSEEVENTF_LEFTUP = &H4
Sub DoDoubleClickAt(x As Long, y As Long)
' Move mouse to position
SetCursorPos x, y
' First click
mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
' Small delay
Application.Wait (Now + TimeValue("0:00:00.1"))
' Second click (double-click)
mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
End Sub
' API to set cursor position
Private Declare PtrSafe Function SetCursorPos Lib "user32" ( _
ByVal x As Long, _
ByVal y As Long) As Long
Sub TestDoubleClick()
' Example: double click at screen coordinate (500, 500)
DoDoubleClickAt 500, 500
End Sub
Notes:
Adjust (500, 500) to the screen pixel coordinates where you want the double click.
This will literally simulate a double-click with your mouse on that spot.
This requires macro security enabled and might be blocked by antivirus software.
PtrSafe keyword used for 64-bit compatibility. Remove it if using 32-bit Office.
If you want to "automatically double click" a file or folder to open it, best to simply use VBA to Shell the executable or open the file:
vba
Sub OpenFile()
Dim filePath As String
filePath = "C:\Path\To\Your\File.xlsx"
' Open file with default associated application
Call Shell("explorer.exe """ & filePath & """", vbNormalFocus)
' Or use Workbooks.Open if Excel file:
' Workbooks.Open filePath
End Sub
Summary
Inside Excel, better to call event procedures directly or perform actions programmatically than "simulate double-click".
Outside Excel, Windows API mouse events can simulate real mouse double clicks.
For opening files, just launch them directly with Shell or Workbooks.Open.
If you specify exactly what you want to double click "automatically," where you want to double-click (on Excel cells, buttons, file explorer, other apps), I can provide a more precise solution.