Sub ImportSheetFromAnotherWorkbook2
' Declare variables
Dim oSourceDoc As Object
Dim oTargetDoc As Object
Dim oSourceSheet As Object
Dim oTargetSheet As Object
Dim sourceFilePath As String
Dim newSheetName As String
Dim dataArray As Variant
' Specify the correct path to the source workbook
sourceFilePath = "file:///C:/Users/chakri/Desktop/New Folder/SPI.ods" ' Update this path
' Load the source workbook
On Error GoTo LoadError
oSourceDoc = StarDesktop.loadComponentFromURL(sourceFilePath, "_blank", 0, Array())
MsgBox "Source Name: " & oSourceDoc.Title
' Get the first sheet from the source workbook
oSourceSheet = oSourceDoc.Sheets(0)
' Get the current document (target workbook)
oTargetDoc = ThisComponent
MsgBox "Current Workbook Name: " & oTargetDoc.Title
' Set the desired name for the new sheet
newSheetName = "SPI_" & Format(Now(), "YYYYMMDD_HHMMSS") ' Add a timestamp
' Insert a new sheet at index 1 (after the first sheet)
positions = oTargetDoc.Sheets.getCount()
On Error GoTo SheetError
oTargetDoc.Sheets.insertNewByName(newSheetName, positions)
oTargetSheet = ThisComponent.Sheets(positions - 1)
MsgBox "Loaded fine"
' Copy data from the source sheet to the target sheet
dataArray = oSourceSheet.getDataArray() ' Get the data array from the source sheet
oTargetSheet.setDataArray(dataArray) ' Set the data in the target sheet
' Close the source workbook without saving changes
oSourceDoc.close(True)
MsgBox "Data imported successfully!"
Exit Sub
LoadError:
MsgBox "Error loading source document: " & Err & " - " & ErrMsg
Exit Sub
SheetError:
MsgBox "Error inserting new sheet: " & Err & " - " & ErrMsg
If Not IsNull(oSourceDoc) Then oSourceDoc.close(True) ' Ensure source is closed on error
Exit Sub
End Sub
您好,我编写了上面的代码来复制和插入其他工作表的数据并插入到当前工作表。但程序因插入纸张时出错而终止。观察结果是,它正在插入一个带有该名称的新工作表,但它说错误并且不允许复制数据。请任何人都可以帮忙解决这个问题。
使用单元格区域(而不是工作表)调用
getDataArray()
。从6.23开始。搜索 Andrew 的宏文档的 Calc 文档:
oCell = oSheet.GetCellbyPosition( 0, 0 )
oCursor = oSheet.createCursorByRange(oCell)
oCursor.GotoEndOfUsedArea(True)
oData = oCursor.getDataArray()