Friday, September 5, 2025

CopyFromSelectedWorkbookToThisWorkbook

 Sub CopyFromSelectedWorkbookToThisWorkbook()

    Dim sourceWB As Workbook

    Dim targetWB As Workbook

    Dim sourceWS As Worksheet

    Dim targetWS As Worksheet

    Dim copyRange As Range

    Dim lastRow As Long, lastCol As Long

    Dim filePath As Variant


    ' Set reference to the target workbook and Sheet1

    Set targetWB = ThisWorkbook

    'Set targetWS = targetWB.ActiveSheet

    Set targetWS = targetWB.Sheets("Sheet1")

    targetWS.cells.clear

    ' Prompt user to select the source workbook (.xls or .xlsx)

    filePath = Application.GetOpenFilename("Excel Files (*.xls; *.xlsx), *.xls; *.xlsx", , "Select Source Workbook")


    ' Exit if user cancels

    If filePath = False Then

        MsgBox "No file selected.", vbExclamation

        Exit Sub

    End If


    ' Open the source workbook

    Set sourceWB = Workbooks.Open(filePath)

    Set sourceWS = sourceWB.ActiveSheet


    ' Find the last used row and column in source sheet

    lastRow = sourceWS.Cells(sourceWS.Rows.Count, 2).End(xlUp).Row

    lastCol = sourceWS.Cells(lastRow, sourceWS.Columns.Count).End(xlToLeft).Column


    ' Define the range to copy

    Set copyRange = sourceWS.Range(sourceWS.Cells(1, 1), sourceWS.Cells(lastRow, lastCol))



    ' Paste the copied range into Sheet1

    copyRange.Copy

    targetWS.Range("A1").PasteSpecial Paste:=xlPasteAll

    ' Optional: Close the source workbook without saving

    sourceWB.Close SaveChanges:=False


    ' Clear clipboard

    Application.CutCopyMode = False


End Sub

Thursday, September 4, 2025

ExportToCSV

 Sub ExportToCSV()

    Dim ws As Worksheet

    Dim exportRange As Range

    Dim lastRow As Long

    Dim filePath As String


    ' Set the worksheet (change Sheet10 to your actual sheet name if needed)

    Set ws = ThisWorkbook.ActiveSheet


    ' Find the last row with data in column A

    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row


    ' Define the range to export (A1 to D[lastRow])

    Set exportRange = ws.Range("A1:D" & lastRow)


    ' Set the file path (you can change this to your desired location)

    filePath = Application.ThisWorkbook.Path & "\ExportedData.csv"


    ' Export the range to CSV

    Open filePath For Output As #1

    Dim r As Range, cell As Range


    For Each r In exportRange.Rows

        Dim line As String

        line = ""

        For Each cell In r.Cells

            line = line & cell.Text & vbTab

        Next cell

        ' Remove trailing tab

        If Len(line) > 0 Then line = Left(line, Len(line) - 1)

        Print #1, line

    Next r

    Close #1



    MsgBox "Data exported to CSV successfully!" & vbCrLf & filePath, vbInformation

End Sub