使用Application.GetOpenFilename导入文本文件

时间:2014-07-19 02:53:31

标签: excel-vba vba excel

我尝试将文本文件的全部内容导入特定工作簿中的特定工作表。我可以在导入另一个Excel文件时使用以下代码使其工作,但我无法弄清楚如何使用文本文件执行相同的概念。我对VBA代码很陌生,所以非常感谢任何帮助!

我每天用于excel导入的示例代码:

Sub Run_NEW_ROB()

    'IDeaS ROB Extract Import

    Cur_file = ActiveWorkbook.Name
    OldFN = Application.GetOpenFilename(, , "Select IDeaS ROB Extract")
    If LCase(OldFN) = "false" Then
    MsgBox "You Did Not Select A File - Stopping"

    Exit Sub
    Else

    Workbooks.Open Filename:=OldFN
    Set WBK = ActiveWorkbook
    End If

    Sheets("Hotel").Select
    Range("A1:Y366").Copy
    Windows(Cur_file).Activate
    Sheets("H_CUR").Select
    Range("A1").Select
    ActiveSheet.Paste
    WBK.Activate
    Application.CutCopyMode = False
    ActiveWindow.Close SaveChanges:=False
    Windows(Cur_file).Activate

    Workbooks.Open Filename:=OldFN
    Set WBK = ActiveWorkbook

    Sheets("Market Segments").Select
    Range("A1:K10221").Copy
    Windows(Cur_file).Activate
    Sheets("SEG_CUR").Select
    Range("A1").Select
    ActiveSheet.Paste
    WBK.Activate
    Application.CutCopyMode = False
    ActiveWindow.Close SaveChanges:=False
    Windows(Cur_file).Activate

End Sub

2 个答案:

答案 0 :(得分:0)

以下是使用 GetOpenFilename 选择并打开目标工作簿的示例。它还使用 GetOpenFilename 来选择文本文件。

将文本导入特定工作表中的特定单元格。然后保存并关闭目标工作簿:

Sub OpenDemo()
    Dim b1 As Workbook, s As String, J As Long

'
'   Select and open the destination workbook
'
    s = Application.GetOpenFilename()
    Workbooks.Open s
    Set b1 = ActiveWorkbook
    Sheets("xxx").Select
'
'   Select and open the text file
'   put the data in B9 and down
'
    s = Application.GetOpenFilename()
    Close #1
    Open s For Input As #1
    J = 9
    Do While Not EOF(1)
        Line Input #1, TextLine
        Cells(J, "B") = TextLine
        J = J + 1
    Loop
    Close #1
'
'   Save and close the destination workbook
'
    b1.Save
    b1.Close

End Sub

答案 1 :(得分:0)

@Gary学生的简单版本。 此版本不会提示您选择目标文件,但会提示您从Win Explorer中选择一个txt文件进行导入。它将txt文件的内容导入到活动工作簿中的活动工作表中,

Sub txtimport()
Dim b1 As Workbook, s As String, J As Long

s = Application.GetOpenFilename()
Close #1
Open s For Input As #1
J = 3
Do While Not EOF(1)
    Line Input #1, TextLine
    Cells(J, "A") = TextLine
    J = J + 1
Loop
Close #1
End Sub