Search code examples
filevbasubroutine

Open a workbook using FileDialog and manipulate it


I found this code here on StackOverflow:

Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    With fd

        .AllowMultiSelect = False
        .Title = "Please select the file to kill his non colored cells"
        .Filters.Add "Excel", "*.xls"
        .Filters.Add "All", "*.*"

        If .Show = True Then
            txtFileName = .SelectedItems(1)
        End If

    End With

I know this code should select a file in FileDialog. However, once I have chosen the .xls file, how do I manipulate the file? In other words, where is my file object for me to manipulate?

I would like someone to continue this code to make some simple manipulation on the workbook so I could learn how to do those simple things on a workbook that I opened.


Solution

  • Here's an example:

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim r As Range
    
    Set wb = Workbooks.Open(txtfilename) ' the file path you selected in FileDialog
    Set ws = wb.Worksheets(1)
    Set r = ws.Cells(1, 1)
    
    With r    
        .Value = "Hello world!"
        .Interior.Color = RGB(255,20,20) 'bright red
    End With