将Excel中的数据保存到工作表中以便稍后写入或加载

时间:2017-09-05 16:20:03

标签: excel vba excel-vba

我有一本工作簿,我正在尝试获取一些插入的数据,并将其保存在新行中以获取新数据。但是,如果输入数据的第一个单元格等于同一列中的另一个单元格而不是我想用新输入的数据写入先前保存的数据。

Sub SmartHBD_Save()

Application.ScreenUpdating = False
Dim StoredJobs As Worksheet
Dim JobNumber As Integer
JobNumber = Sheets("Stored Jobs").Range("B" & Rows.Count).End(xlUp).Row

Dim c As Range
For Each c In Sheets("Stored Jobs").Range("B4:B" & JobNumber)
Set StoredJobs = Worksheets("Stored Jobs")
If c.Value = B2 Then
    StoredJobs.Range("B2:AO2").Copy
    StoredJobs.Cells(JobNumber, 1).End(xlUp).PasteSpecial xlPasteValues
Else
    StoredJobs.Range("B2:AO2").Copy
    StoredJobs.Cells(Rows.Count, 1).End(xlUp).Offset(1, 1).PasteSpecial xlPasteValues
End If
Next c

Application.CutCopyMode = False
Application.ScreenUpdating = True

End Sub

我让它在新行上保存数据但是当我试图让它覆盖数据时它停止工作。

1 个答案:

答案 0 :(得分:0)

测试:

Sub SmartHBD_Save()

    Dim StoredJobs As Worksheet
    Dim lastRow As Long
    Dim f As Range, theJob

    Set StoredJobs = Worksheets("Stored Jobs")
    lastRow = StoredJobs.Range("B" & Rows.Count).End(xlUp).Row

    theJob = StoredJobs.Range("B2").Value

    'find the current job if it exists
    Set f = StoredJobs.Range("B4:B" & lastRow).Find(what:=theJob, lookat:=xlWhole)

    'if not found, use the next empty row
    If f Is Nothing Then Set f = StoredJobs.Range("B" & (lastRow + 1))

    'B1:AO1 is *relative* to f.EntireRow
    f.EntireRow.Range("B1:AO1").Value = StoredJobs.Range("B2:AO2").Value

End Sub