将文本文件导入新工作表,执行某些操作,然后关闭工作表

时间:2015-07-10 11:16:12

标签: vba excel-vba import text-files excel

我有一个问题,我需要帮助解决。我想将文本文件导入新的临时表,查找一些数据,将它们放在我当前的表中,然后关闭新的临时表。这可能吗?我该怎么做?

2 个答案:

答案 0 :(得分:1)

要创建新的工作表,请将其删除:

Option Explicit

Sub openWorkSheet()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets.Add(, ThisWorkbook.ActiveSheet)
End Sub

Sub closeWorkSheet(ByRef ws As Worksheet)
    If Not ws Is Nothing Then
        With Application
            .DisplayAlerts = False
            ws.Delete
            .DisplayAlerts = True
        End With
    End If
End Sub

要打开文本文件,请阅读其内容并查找特定字符串:

Public Sub searchFile(ByVal filePathAndName As String)

    Const TYPICAL_START = "FIRST search string"
    Const TYPICAL_END = "LAST search string"

    Dim fso As Object
    Dim searchedFile As Object
    Dim fullFile As String
    Dim foundStart As Long
    Dim foundEnd As Long
    Dim resultArr() As String
    Dim i As Long

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set searchedFile = fso.OpenTextFile(filePathAndName)

    fullFile = searchedFile.ReadAll 'read entire file

    i = 1
    foundStart = 1
    foundStart = InStr(foundStart, fullFile, TYPICAL_START, vbTextCompare)

    If foundStart > 0 Then

        foundEnd = InStr(foundStart, fullFile, TYPICAL_END, vbTextCompare)

        While foundStart > 0 And foundEnd > 0
            ReDim Preserve resultArr(i)
            resultArr(i) = Mid(fullFile, foundStart, foundEnd - foundStart + 1)
            foundStart = InStr(foundStart + 1, fullFile, TYPICAL_START, vbTextCompare)
            If foundStart > 0 Then foundEnd = InStr(foundStart, fullFile, TYPICAL_END)
            i = i + 1
        Wend
    End If
End Sub

答案 1 :(得分:0)

所以现在它已经成功了。这是不想工作的子。

Sub Import()

   Dim DestBook As Workbook, SourceBook As Workbook
   Dim DestCell As Range
   Dim RetVal As Boolean

   ' Set object variables for the active book and active cell.
   Set DestBook = ActiveWorkbook
   Set DestCell = ActiveCell

   ' Show the Open dialog box.
   RetVal = Application.Dialogs(xlDialogOpen).Show("*.txt", , True)

   ' If Retval is false (Open dialog canceled), exit the procedure.
   If RetVal = False Then Exit Sub

   ' Set an object variable for the workbook containing the text file.
   Set SourceBook = ActiveWorkbook

   ' Copy the contents of the entire sheet containing the text file.
   Range(Range("A1"), Range("A1").SpecialCells(xlLastCell)).Copy

   ' Activate the destination workbook and paste special the values
   ' from the text file.
   DestBook.Activate
   DestCell.PasteSpecial Paste:=xlValues

   ' Close the book containing the text file.
   SourceBook.Close False

End Sub