我想删除excel单元格中的数据,从第二个单元格开始,列为:F,G,H,I,J,K,L,M到数据末尾。
我尝试解决此问题的代码如下所示,但我相信在这些列中删除所有数据到数据结尾应该有更好的答案:
Private Sub DeleteData()
Dim x
Dim y
Dim LastRow
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\Master.xls", 0, True)
' ## Open both workbooks first:
Set x = xlApp.Workbooks.Open("C:\Master.xls")
' Now, copy what you want from x:
xlApp.Sheets("Data").Range("K:K").Copy
Set y = xlApp.Workbooks.Open("C:\SuiteOne.xls")
' Now, paste to y worksheet:
y.Sheets("SuiteOneCaseFour").Range("E:E").PasteSpecial
'AutoFit
y.Sheets("SuiteOneCaseFour").Range("E:E").Columns.AutoFit
'Clear fields
LastRow = y.Sheets("SuiteOneCaseFour").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
y.Sheets("SuiteOneCaseFour").Range("F2:M" & LastRow).ClearContents
x.Save
x.Close
y.Save
y.Close
End Sub
DeleteData()
答案 0 :(得分:0)
Dim LastRow As Long
LastRow = y.Sheets("SuiteOneCaseFour").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
y.Sheets("SuiteOneCaseFour").Range("F2:M" & LastRow).ClearContents
答案 1 :(得分:0)
尝试以下修正代码:
Option Explicit
Private Sub DeleteData()
Dim x As Workbook
Dim y As Workbook
Dim LastRow As Range
Application.ScreenUpdating = False
Set x = Workbooks.Open("C:\Master.xls")
x.Sheets("Data").Range("K:K").Copy
Set y = Workbooks.Open("C:\SuiteOne.xls")
With y.Sheets("SuiteOneCaseFour")
.Range("E:E").PasteSpecial
.Range("E:E").Columns.AutoFit
Set LastRow = .Cells.Find(What:="*", After:=ActiveCell, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not LastRow Is Nothing Then
.Range("F2:M" & LastRow.Row).ClearContents
End If
End With
x.Save
x.Close
y.Save
y.Close
Application.ScreenUpdating = True
End Sub