可在 MS Excel 和 LibreOffice Calc 中运行的宏

可在 MS Excel 和 LibreOffice Calc 中运行的宏

我有一个电子表格,用户将在 Excel 和 LibreOffice Calc 中使用。我想设计可以在两者中使用的宏。我考虑的代码是:如果 Excel 则 [VBA 代码],否则 [Basic 或 Python 代码]

我认为两个关键点是两个程序都可以读取的 IF/THEN 语句(或等效语句),以及确保两个程序都会忽略对它们不适用的代码的方法。

我已经尝试在 LibreCalc 中运行它,但它不起作用。这是我需要在 Excel 和 Calc 中运行的代码:

Public Sub spubInsertCurrDateTimeText()
'DESCRIPTION:  inserts current date and time into the active cell in text format.

Dim dtmNow As Date
Dim CurrTemp As Date
Dim CurrTot As Date
Dim NewTot As Date
Dim StartCol As Integer
Dim StopCol As Integer
Dim ClockTimerCol As Integer
Dim TotalTimeCol As Integer

dtmNow = Now 'sets variable to value of function NOW (current date/time)
StartCol = 1 'this is the column where the user enter the starting time
StopCol = 2 'this is the column where the user enter the ending or stop time
ClockTimerCol = 3 'this is the column that calculates elapsed time (StopCol minus StartCol)
TotalTimeCol = 4 'this is the column that tracks the total time elapsed in minutes

If ActiveCell.Column = StartCol Then

ActiveCell = dtmNow 'inserts variable into the active cell
Worksheets(ActiveSheet.Name).Cells(ActiveCell.Row, StopCol).Value = 0

ElseIf ActiveCell.Column = StopCol Then

ActiveCell = dtmNow 'inserts variable into the active cell

CurrTot = Worksheets(ActiveSheet.Name).Cells(ActiveCell.Row, TotalTimeCol).Value
CurrTemp = Worksheets(ActiveSheet.Name).Cells(ActiveCell.Row, ClockTimerCol).Value

NewTot = CurrTot + (CurrTemp * 1440)

Worksheets(ActiveSheet.Name).Cells(ActiveCell.Row, TotalTimeCol).Value = NewTot

Worksheets(ActiveSheet.Name).Cells(ActiveCell.Row, StartCol).Value = 0
Worksheets(ActiveSheet.Name).Cells(ActiveCell.Row, StopCol).Value = 0

Else

ActiveCell = dtmNow 'inserts variable into the active cell

End If

End Sub

有什么建议么?

答案1

Calc 的 API 与 Excel 的 API 有很大不同,因此尽管 VBA 与 StarBasic 有很多相似之处,但您仍需要编写单独的代码来处理不同的 API 调用。要测试正在处理的文件是否为 Calc,请在 StarBasic 中执行以下操作:

If oDoc.supportsService("com.sun.star.sheet.SpreadsheetDocument") Then
    REM Run code for Calc
Else
    REM Run code for Excel
End If

我发现更大的问题是,您谈论的是从电子表格内部运行此代码。如果电子表格保存为 .xls 或 .xlsx,则 OpenOffice 和 LibreOffice 将在打开文件时禁用任何宏。我相信,如果电子表格保存为 .ods 文件,Excel 的情况则相反。即使您正确编写了所有代码,至少有一个程序会拒绝执行它。

虽然外部程序可以测试打开电子表格并执行适用的代码块的是 Excel 还是 Calc,但我认为这无法与电子表格中嵌入的任何宏一起使用。

相关内容