2014-06-14 53 views
0

我已經使用VB代碼編寫了下面的代碼,用於從MS Excel中生成記事本格式的數據。 我在記事本中獲取文件,但問題是,如果在Excel中有多個工作表,那麼我也得到一個提取。我想在diff文件中獲取所有工作表的摘錄。使用Visual Basic從MS Excel中提取數據時面臨的問題

請建議。

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _ 
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long 

Private Const MAX_PATH As Long = 260 

'~~> Change this where and how you want to save the file 
Const FlName = "C:\My\excel\MyWorkbook.vbs" 

Sub Sample() 
    Dim tmpFile As String 
    Dim MyData As String, strData() As String 
    Dim entireline As String 
    Dim filesize As Integer 

    '~~> Create a Temp File 
    tmpFile = "C:\My\excel\Sheet1.vbs" 

    ActiveWorkbook.SaveAs Filename:=tmpFile _ 
    , FileFormat:=xlText, CreateBackup:=False 

    '~~> Read the entire file in 1 Go! 
    Open tmpFile For Binary As #1 
    MyData = Space$(LOF(1)) 
    Get #1, , MyData 
    Close #1 
    strData() = Split(MyData, vbCrLf) 

    '~~> Get a free file handle 
    filesize = FreeFile() 

    '~~> Open your file 
    Open FlName For Output As #filesize 

    For i = LBound(strData) To UBound(strData) 
     entireline = Replace(strData(i), """", "") 
     '~~> Export Text 
     Print #filesize, entireline 
    Next i 

    Close #filesize 

    MsgBox "Done" 
End Sub 

'Function TempPath() As String 
    'TempPath = String$(MAX_PATH, Chr$(0)) 
    'GetTempPath MAX_PATH, TempPath 
    'TempPath = Replace(TempPath, Chr$(0), "") 
'End Function 
+0

大家好,請建議如何在多個工作表中得到結果 – user3310812

回答

0

當您使用語句ActiveWorkbook.SaveAs ...時,您將一次保存所有工作表。相反,循環通過工作表,並分別保存每一個...

For Each Sheet In ActiveWorkbook.Sheets 

    Sheet.SaveAs Filename:=tmpFile, FileFormat:=xlText, CreateBackup:=False 

    ' Open and process the file... 

Next