2014-02-12 72 views
2

我發現這個代碼在這裏StackOverflow上:使用FileDialog的打開工作簿,並操縱它

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 

我知道這個代碼應該在FileDialog選擇一個文件。 但是,一旦我選擇了.xls文件,我該如何操作文件?換句話說,我的文件對象在哪裏操作?

我希望有人繼續這段代碼對工作簿進行一些簡單的操作,以便我可以學習如何在打開的工作簿上完成這些簡單的事情。

回答

1

下面是一個例子:

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 
4

有你兩種方法(我喜歡用第一個)。在兩種方法wb變量商店打開工作簿。我評論了詳細的代碼,但如果你有一些問題 - 問:)

第一種方法:

Sub test1() 
    Dim xlFileName 
    Dim wb As Workbook 

    xlFileName = GetOpenFilename("Excel (*.xls*),*.xls*", 1, _ 
     "Please select the file to kill his non colored cells") 

    'if user pressed CANCEL - exit sub 
    If xlFileName = False Then 
     MsgBox "User pressed CANCEL" 
     Exit Sub 
    End If 

    'Tries to open workbook with choosen file name 
    On Error Resume Next 
    Set wb = Application.Workbooks.Open(xlFileName) 
    On Error GoTo 0 

    'If we can't find workbook with choosen path, exit Sub 
    If wb Is Nothing Then 
     MsgBox "Can't find file" 
     Exit Sub 
    End If 

    'your code here 
    wb.Worksheets("Sheet1").Range("A1").Value = "test" 

    'close workbook with saving changes 
    wb.Close SaveChanges:=True 
    Set wb = Nothing 

End Sub 

第二種方法:

Sub test() 
    Dim xlFileName As String 
    Dim fd As Office.FileDialog 
    Dim wb As Workbook 

    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 Then 
      xlFileName = .SelectedItems(1) 
     Else 
      'if user pressed CANCEL - exit sub 
      MsgBox "User pressed CANCEL" 
      Exit Sub 
     End If 

    End With 

    'Tries to open workbook with choosen file name  
    On Error Resume Next 
    Set wb = Workbooks.Open(xlFileName) 
    On Error GoTo 0 

    'If we can't find workbook with choosen path, exit Sub 
    If wb Is Nothing Then 
     MsgBox "Can't find file" 
     Exit Sub 
    End If 

    'your code here 
    wb.Worksheets("Sheet1").Range("A1").Value = "test" 

    'close workbook with saving changes 
    wb.Close SaveChanges:=True 
    Set wb = Nothing 

End Sub 
相關問題