Import txt file with open file dialog box and brea

2019-07-29 12:46发布

I Know I am doing a mistake after the line: If intChoice <> 0 Then
Can someone help me to rectify it?

Private Sub CommandButton1_Click()
    Dim intChoice As Integer
    'Select the start folder
    Application.FileDialog(msoFileDialogOpen).InitialFileName = "I:\Dunnings"
    'make the file dialog visible to the user
    intChoice = Application.FileDialog(msoFileDialogOpen).Show
    'determine what choice the user made

    If intChoice <> 0 Then
        Workbooks.OpenText.Filename:= intChoice, Origin:=xlMSDOS, StartRow:=23, DataType:=xlFixedWidth, FieldInfo:= _
            Array(Array(0, 1), Array(6, 2), Array(23, 1), Array(30, 2), Array(63, 2), Array(68, 1), _
            Array(77, 4), Array(88, 4), Array(101, 1), Array(117, 1)), TrailingMinusNumbers:= _
            True
        NewPath = Mid(ThisWorkbook.FullName, 1, _
        Len(ThisWorkbook.FullName) - Len(ThisWorkbook.Name)) & "\" & _
            "Dunnings - " & Format(Date, "dd-mm-yyyy") & ".xlsm"
        ThisWorkbook.SaveAs (NewPath)
    End If
End Sub

2条回答
淡お忘
2楼-- · 2019-07-29 13:12
Private Sub CommandButton1_Click()
    With Application.FileDialog(msoFileDialogOpen)
        .InitialFileName = "I:\"
        .Filters.Clear
        .Title = "Your Title"
        If Not .Show Then
            MsgBox "No file selected.": Exit Sub
        End If
        Workbooks.OpenText .SelectedItems(1), Origin:=xlMSDOS, StartRow:=23, _
                DataType:=xlFixedWidth, FieldInfo:=Array(Array(0, 1), Array(6, 2), _
                Array(23, 1), Array(30, 2), Array(63, 2), Array(68, 1), _
                Array(77, 4), Array(88, 4), Array(101, 1), Array(117, 1)), _
                TrailingMinusNumbers:=True
        NewPath = Mid(ThisWorkbook.FullName, 1, _
            Len(ThisWorkbook.FullName) - Len(ThisWorkbook.Name)) & "\" & _
            "Dunnings - " & Format(Date, "dd-mm-yyyy") & ".xlsm"
        ThisWorkbook.SaveAs (NewPath)
    End With
End Sub

Basically the rest of the code can be recorded using RecordMacro and then copy resulting code to your VB code.

查看更多
仙女界的扛把子
3楼-- · 2019-07-29 13:23

IntChoice is integer.
Filename argument expects string. Something like this:

With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Dunnings"
    .Filters.Clear
    .title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1) 'and the rest of your code.
End With
查看更多
登录 后发表回答