所以我已经使用CSV文件导出了数据,但截至目前它只是原始数据。我正在尝试dsiplay它来自的文件名和工作表名称。这是我的代码到目前为止导出数据。下面的宏从打开的Excel工作表中导出数据,我只运行宏并将数据导出到新的工作簿中。现在我只想显示从我创建的新CSV文件中导出的源文件名和工作表名称。
Sub 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 :(得分: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
答案 1 :(得分: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