使用XLSXApp对象修改XLSX文件,Sheet1的某些单元格的内容
打开工程,添加按钮,标题改成修改内容双击按钮,添加如下代码运行Test2.xlsx文件内容Private Sub Command4_Click()
Dim DoXLSX As XLSXApp
Dim MaxRow As Integer
Dim MaxCol As Integer
Dim i As Integer
Dim j As Integer
Dim Data_Before As String
Dim Data_After As String
Dim Error As String
Set DoXLSX = New XLSXApp
'打开XLSX文件
If DoXLSX.Open("Test1.xlsx", Error) = False Then
MsgBox Error
Set DoXLSX = Nothing
Exit Sub
End If
'选择Sheet1
If DoXLSX.SelSheet("Sheet1", Error) = False Then
DoXLSX.Close
Set DoXLSX = Nothing
MsgBox Error
Exit Sub
End If
'读取Excel行和列信息
MaxRow = DoXLSX.GetRowTotal
MaxCol = DoXLSX.GetColumnCount
If MaxRow = 0 Or MaxCol = 0 Then
DoXLSX.Close
Set DoXLSX = Nothing
MsgBox "没有数据!"
Exit Sub
End If
'读取修改前的数据
Data_Before = ""
For i = 1 To MaxRow
If i > 1 Then Data_Before = Data_Before & vbCrLf
For j = 1 To MaxCol
If j > 1 Then Data_Before = Data_Before & vbTab
Data_Before = Data_Before & DoXLSX.Rs(j, i)
Next
Next
'修改数据
DoXLSX.SetCellValue 1, 1, "你好AAA"
DoXLSX.SetCellValue 2, 2, 12.25
DoXLSX.SetCellValue 1, 3, 12.25
'读取Excel行和列信息
MaxRow = DoXLSX.GetRowTotal
MaxCol = DoXLSX.GetColumnCount
If MaxRow = 0 Or MaxCol = 0 Then
DoXLSX.Close
Set DoXLSX = Nothing
MsgBox "没有数据!"
Exit Sub
End If
'读取修改后的数据
Data_After = ""
For i = 1 To MaxRow
If i > 1 Then Data_After = Data_After & vbCrLf
For j = 1 To MaxCol
If j > 1 Then Data_After = Data_After & vbTab
Data_After = Data_After & DoXLSX.Rs(j, i)
Next
Next
'关闭XLSX文件
DoXLSX.SaveAs "Test2.xlsx"
DoXLSX.Close
Set DoXLSX = Nothing
MsgBox "修改前数据" & vbCrLf & Data_Before & vbCrLf & vbCrLf & "修改后数据" & vbCrLf & Data_After
End Sub