VBA - 日期的.NumberFormat错误

时间:2016-03-16 07:27:10

标签: vba excel-vba excel

我的问题是我的专栏DATE的格式为Mar 16 2016 3:19PM。我运行代码所需的格式是3/16/2016,现在我尝试转换它。这是我使用我的代码时遇到的错误:

  

运行时错误' 13'类型不匹配

这是我收到错误的行

data = Intersect(Sheet2.Columns("O"), Sheet2.UsedRange).NumberFormat = "mm/dd/yyyy"

这是我的代码:

Public Sub Selection()

Dim file2 As Excel.Workbook
Dim Sheet2 As Worksheet, data(), i&

    Set Sheet2 = Workbooks.Open(TextBox2.Text).Sheets(1)

    ' load the data from column O
    data = Intersect(Sheet2.Columns("O"), Sheet2.UsedRange).NumberFormat = "mm/dd/yyyy"
    'set the title
    data(1, 1) = "Month"
    ' extract the month
    For i = 2 To UBound(data)
    If VarType(data(i, 1)) = vbDate Then
      data(i, 1) = Month(data(i, 1))
    End If
  Next

  ' write the data back to the sheet
  Sheet2.UsedRange.Columns(Sheet2.UsedRange.Columns.Count + 1) = data

End Sub

我尝试过使用:

outputWksht.Columns(24).NumberFormat = "mm/dd/yyyy"

Cells(1, 1).Value = Format(StartDate, "dd/mm/yyyy")

没有错误,但它不起作用,我想知道为什么?

3 个答案:

答案 0 :(得分:0)

你能尝试一下这个吗?

Cells(1, 5).NumberFormat = "dd/mm/yyyy"

答案 1 :(得分:0)

尝试

  Dim data As Range
  Set data = Intersect(Sheet2.Columns("O"), Sheet2.UsedRange)
  data.NumberFormat = "mm/dd/yyyy"

答案 2 :(得分:0)

尝试更改此内容:

  For i = 2 To UBound(data)
  If VarType(data(i, 1)) = vbDate Then
    data(i, 1) = Month(data(i, 1))
  End If
Next

到此:

For i = 2 To UBound(data)
  data(i, 1) = Month(CDate(data(i, 1)))
Next i