【发布时间】:2017-10-31 05:40:19
【问题描述】:
我正在尝试将一系列日期从文本转换为“日期”格式,它们位于“主”表的 B 列中。
我创建了一个宏,但我想从任何工作表运行它,而不是在主工作表上。但是,错误代码“下标超出范围”不断出现,突出显示 With Sheets("sh2")。我到目前为止的代码是:
Sub DateFormatUpdate()
DateFormatUpdate Macro
Updates the format of the dates in the master data sheet from 'General' to 'Date'
Dim sh2 As Worksheet
Set sh2 = ActiveWorkbook.Sheets("Master")
With Sheets("sh2")
Range("B2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.TextToColumns Destination:=Range("B2"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
:=Array(1, 5), TrailingMinusNumbers:=True
Range("C2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.TextToColumns Destination:=Range("C2"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
:=Array(1, 5), TrailingMinusNumbers:=True
Range("R9").Select
End With
End Sub
我对 VBA 很陌生,所以如果这实际上是一个简单的问题,我深表歉意!感谢您的帮助!
【问题讨论】:
-
你有
With语句,但永远不要用它来锚定你的范围。在With中,您需要使用.将Range/Cells锚定到该工作表/变量。 IE。With sh2 // .Range("B2").Select ...。另外,请注意,最好avoid using.Select/.Activate` -
^^ 加上您不能
Select工作表上的范围,除非它是活动工作表。这是摆脱Select的另一个原因,而不是Activate工作表的原因。
标签: vba excel text-to-column