在VBA for Excel 2016中通过msoFileDialogOpen打开时无法编辑文件

时间:2016-11-23 10:39:38

标签: excel vba excel-vba

我要做的是打开一个扩展名为.csv的文件,搜索一个字符串,然后用另一个字符串替换它。我是通过msoFileDialogOpen和Selection.Replace完成的。 Windows资源管理器打开,我可以搜索,但无论我做什么,.csv文件中的数据都不会显示在Excel中。有趣的是,我有另一个宏与完全相同的msoFileDialogOpen代码,并在那里工作。还尝试复制/粘贴此代码并进行调整,但没有。

我真的不知道这是什么以及如何解决它。我尝试了不同的代码,但不幸的是它们不起作用。这是我的代码:

     Private Sub Comma()
    ' Opens the Windows File Explorer, so you can select csv files
        Dim dlgResult
        Dim ofd As FileDialog
        Set ofd = Application.FileDialog(msoFileDialogOpen)
            With ofd
              .AllowMultiSelect = False
              .Filters.Clear
              .Filters.Add "CSV files", "*.csv", 1
              .Show
        If .SelectedItems.Count <> 0 Then
            dlgResult = .SelectedItems.Item(1)
        Else
            MsgBox "You selected Cancel. Macro will now exit"
        Exit Sub
    End If
    End With
' This removes the annoying unnecessary double qoute within the logfiles, so you can actually run the csv macro without screwing everything up
    dlgResult = "TEXT;" & dlgResult
        With ActiveSheet.QueryTables.Add(Connection:= _
            dlgResult, _
            Destination:=Range("$A$1:$P$9999"))
            Range("A1:P5000").Select
            Selection.Replace What:="""", Replacement:="", LookAt:=xlPart, _
                SearchOrder:=xlByRows, MatchCase:=False
            ThisWorkbook.RefreshAll

            Selection.Replace What:=",,", Replacement:="", LookAt:=xlPart, _
                SearchOrder:=xlByRows, MatchCase:=False
            ThisWorkbook.RefreshAll

            Selection.Replace What:=",,", Replacement:=",", LookAt:=xlPart, _
                SearchOrder:=xlByRows, MatchCase:=False
            ThisWorkbook.RefreshAll


    ' This will overwrite the logfile.
        ThisWorkbook.SaveCopyAs _
        Filename:="C:\Dir\Dir\Dir\Dir\Dir" & "\" & _
        ThisWorkbook.Name
            MsgBox "File saved in the Logs directory."

    ' This will clear the sheet and opens the menu again, so you can continu with the next macro
    '   Application.DisplayAlerts = False
    '   Worksheets("Sheet1").Range("A1:P5000").Clear
    '   Application.DisplayAlerts = True
        MacroSelect.Show
    End With
    End Sub

提前致谢

0 个答案:

没有答案