2014-09-24 142 views
1

因此,我已經使用CSV文件導出數據,但截至目前它只是原始數據。我正在嘗試dsiplay它來自的文件名和表名。這是我迄今從導出數據的代碼。下面的宏從一個打開的Excel工作表導出數據,我只是運行宏並將數據導出到一個新的工作簿中。現在我只想顯示從我創建的新CSV文件中導出的源文件名和表名。將數據導出到CSV文件並檢索文件名

子testexport()

' export Macro 

Range("B7:E26,B39:E138").Select 
Selection.Copy 
Workbooks.Add 
ActiveSheet.Paste 
ActiveWorkbook.SaveAs Filename:= _ 
"Y:\SQCData.csv" _ 
, FileFormat:=xlCSV, CreateBackup:=False 
Application.DisplayAlerts = False 
ActiveWorkbook.Activate 
Application.DisplayAlerts = True 

以下範圍,它顯示包含我的數據。現在我的問題是...如何在導出後在同一張Excel表格上顯示文件名稱和表格名稱?

+0

你是如何命名的CSV導出的文件?它們是基於sheetname嗎? – 2014-09-24 14:24:07

+0

種類,我想獲得工作簿名稱以及頂部列中的工作表名稱,然後顯示數據。 – adit123 2014-09-24 14:29:07

回答

0

你可以調整這個

Sub CopyPasteBetween2Books() 

Dim wb As Workbook 

    ThisWorkbook.Sheets(1).Range("B7:E26,B39:E138").Copy 
    wbname2 = ThisWorkbook.Name 
    wsname2 = ActiveSheet.Name 
    Workbooks.Add 
    ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range("A1") 
    wbname = "Y:\SQCData.csv" 
    ActiveWorkbook.SaveAs wbname 
    Set wb = Workbooks.Open("Y:\SQCData.csv") 
    wb.Activate 
    ActiveCell.Offset(0, 8).Value = wbname2 
    ActiveCell.Offset(0, 9).Value = wsname2 


    Application.CutCopyMode = False 
End Sub 
+0

我試過這段代碼,它只顯示新創建的工作簿名稱和工作表。對不起,我應該澄清,我想從我從中導出的工作簿的工作簿名稱和工作表名稱。 – adit123 2014-09-24 14:41:15

+0

謝謝你的答案! – adit123 2014-09-24 14:44:46

+0

@ adit123編輯代碼以獲取源工作簿/工作表名稱 – mrbungle 2014-09-24 14:55:20

0
Sub GetFileNameandSheet() 

' assign variables 
Dim strFolder As String 
Dim strFile As String 
Dim latestFile As String 
Dim dtLast As Date 

strFolder = "C:\MyFolder\"   ' sets search path - put the directory where you saved the file here - enclose in quotes 
strFile = Dir(strFolder & "\*.xls*", vbNormal) ' looks for ,csv files only 

' This loops through files to find latest modified date 
    Do While strFile <> "" 
     If FileDateTime(strFolder & strFile) > dtLast Then 
      dtLast = FileDateTime(strFolder & strFile) 
      latestFile = strFolder & strFile 
     End If 
     strFile = Dir 
    Loop 

' The following will write the latest file name and sheet to 2 cells on the active sheet 
Range("XX") = latestFile   ' writes the latest .csv file name in your folder - substitute the cell location were you want the data 
Range("XY") = ActiveSheet.Name 'writs the Active Sheet name 

End Sub 
+0

謝謝你的回答。對不起,我應該澄清,我想顯示我從CSV文件導出的工作簿的工作簿名稱和工作表名稱。 – adit123 2014-09-24 14:44:07