用于Windows的Excel编写的VBA无法在Mac上运行

时间:2015-04-20 11:44:27

标签: excel macos vba excel-vba

我有一组宏可以根据特定行的内容隐藏和取消隐藏列。它们都是用Excel 2013 for Windows编写的(与我的MBA相似,如果相关的话)并在那里工作得很好。但是当我在Excel 2011 for Mac中打开工作表时,宏会给出奇怪的结果。 "取消隐藏所有列"宏工作正常;其他函数可以隐藏所有列,但不能取消隐藏我想看到的列。

我只能假设Excel for Mac在FOR EACH循环中遇到问题,但我无法弄清楚是什么!我很感激任何指导:我需要让这个系统在Windows和Mac上运行。

以下代码。

此功能有效:

Sub GANTT_Filter_Show_All()

Dim rngDates As Range

Set rngDates = Range("GANTT_Dates")

rngDates.EntireColumn.Hidden = False

End Sub

但这只隐藏了所有列:

Sub GANTT_Filter_This_Quarter()

Dim intCurrentMonth As Integer, intCurrentYear As Integer, rngDates As Range, cell As Range
Dim intCurrentQuarterMonths(3) As Integer

Set rngDates = Range("GANTT_Dates")
intCurrentMonth = DatePart("m", Date)
intCurrentYear = DatePart("yyyy", Date)

'loading months of current quarter into an array intCurrentMonth

Select Case intCurrentMonth
    Case 1 To 3
        intCurrentQuarterMonths(0) = 1
        intCurrentQuarterMonths(1) = 2
        intCurrentQuarterMonths(2) = 3
    Case 4 To 6
        intCurrentQuarterMonths(0) = 4
        intCurrentQuarterMonths(1) = 5
        intCurrentQuarterMonths(2) = 6
    Case 7 To 9
        intCurrentQuarterMonths(0) = 7
        intCurrentQuarterMonths(1) = 8
        intCurrentQuarterMonths(2) = 9
    Case 10 To 12
        intCurrentQuarterMonths(0) = 10
        intCurrentQuarterMonths(1) = 11
        intCurrentQuarterMonths(2) = 12
    End Select

'hiding all columns

rngDates.EntireColumn.Hidden = True

'comparing each column to array of months in current quarter and hiding if false

For Each cell In rngDates
    For Each v In intCurrentQuarterMonths
        If v = DatePart("m", cell.Value) And DatePart("yyyy", cell.Value) = intCurrentYear Then cell.EntireColumn.Hidden = False
    Next v
Next cell

Application.Goto Reference:=Range("a1"), Scroll:=True

End Sub

1 个答案:

答案 0 :(得分:0)

我和@Steven在这个问题上,代码没有明显错误。我不是Mac用户,但完全有可能在日期函数周围出现一些奇怪现象,尤其是那些需要格式化才能解决的问题。

在这样的情况下,我会尝试使用对Month()和Year()的调用替换对DatePart()的调用 - 即使对于非Mac用户也是如此。它不依赖于解析字符串进行格式化,因此它更有效(并且易于阅读):

Sub Benchmarks()

    Dim starting As Double, test As Date, i As Long
    test = Now

    starting = Timer
    For i = 1 To 1000000
        Year test
    Next i
    Debug.Print "Elapsed: " & (Timer - starting)

    starting = Timer
    For i = 1 To 1000000
        DatePart "yyyy", test
    Next i
    Debug.Print "Elapsed: " & (Timer - starting)

End Sub

因为您可能无法运行基准测试......

Elapsed for Year():     0.109375
Elapsed for DatePart(): 0.515625

另请注意,除此之外,您要搜索的列中的日期作为变体发布,它可能有助于将它们明确地转换为日期:

If v = Month(CDate(cell.Value)) And intCurrentYear = Year(CDate(cell.Value)) Then
    cell.EntireColumn.Hidden = False
End If