我有许多从 CSV 导入的工作表。数据包括基于 UNIX 纪元的时间戳。每次导入新工作表时,我都需要添加一列以将时间戳转换为人类可读的时间。
我用记录一个宏开始并得到了这个结果:
Sub addnamedtable()
'
' addnamedtable Macro
' Takes the imported data, converts it to a table and then adds a column which uses a formula to read the epoch based date stamp
'
Range("A1:N5614").Select
ActiveSheet.QueryTables("Temp6").Delete
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$N$5614"), , xlYes).Name = _
"Table2"
Range("Table2[#All]").Select
ActiveWindow.ScrollColumn = 2
ActiveWindow.ScrollColumn = 3
ActiveWindow.ScrollColumn = 4
ActiveWindow.ScrollColumn = 5
ActiveWindow.ScrollColumn = 6
ActiveWindow.ScrollColumn = 7
ActiveWindow.ScrollColumn = 8
ActiveWindow.ScrollColumn = 9
ActiveWindow.ScrollColumn = 10
ActiveWindow.ScrollColumn = 11
Range("O2").Select
ActiveCell.FormulaR1C1 = "=[@[s:timestamp]]/(60*60*24*1000)+""1/1/1970"""
Range("Table2[[#Headers],[Column1]]").Select
ActiveCell.FormulaR1C1 = "Real_Date"
Range("O2").Select
End Sub
然后我开始取出细节并替换它们,以便它适用于任何工作表和范围,而不仅仅是我记录的特定工作表。这就是我现在所拥有的。
Sub addnamedtable()
'
' Takes the imported data, converts it to a table and then adds a column which uses a formula to read the epoch based date stamp
'
Dim tempname As String
Set tempname = ActiveSheet.Name
Cells.Select
ActiveSheet.QueryTables(ActiveSheet.Name).Delete
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$N$5614"), , xlYes).Name = _tempname
Range(tempname & "[#All]").Select
Range("O2").Select
ActiveCell.FormulaR1C1 = "=[@[s:timestamp]]/(60*60*24*1000)+""1/1/1970"""
Columns("O:O").Select
Cells.SpecialCells(xlLastCell).Select
Columns(ActiveCell.Column).Select
Selection.NumberFormat = "m/d/yyyy h:mm"
Range(tempname & "[[#Headers],[Column1]]").Select
ActiveCell.FormulaR1C1 = "Date"
End Sub
我无法将工作表名称作为值分配给 tempname 字符串。之后,我需要根据工作表命名表,以避免将来在工作簿中发生冲突。
最后的东西也可能是胡说八道,但宏还没有跑那么远来测试它。
编辑继@Head of Catering 的回答之后
Sub addnamedtable()
'
' addnamedtable Macro
'
Dim tempname As String
Dim temprange As Range
tempname = ActiveSheet.Name
Cells.Select
Set temprange = Selection
ActiveSheet.QueryTables(ActiveSheet.Name).Delete
ActiveSheet.ListObjects.Add(xlSrcRange, Range(temprange), , xlYes).Name = _
tempname
Range(tempname & "[#All]").Select
Range("O2").Select
ActiveCell.FormulaR1C1 = "=[@[s:timestamp]]/(60*60*24*1000)+""1/1/1970"""
Columns("O:O").Select
Cells.SpecialCells(xlLastCell).Select
Columns(ActiveCell.Column).Select
Selection.NumberFormat = "m/d/yyyy h:mm"
Range(tempname & "[[#Headers],[Column1]]").Select
ActiveCell.FormulaR1C1 = "Real_Date"
End Sub
运行这个给了我错误
对象“_Global”的块引用方法“范围”失败
我认为这意味着它不承认temprange
作为一个范围的价值。我试过temprange.address
了,但这导致 excel 在没有反馈的情况下锁定