我的VBA宏正在运行,但我需要将其粘贴为值

时间:2017-01-31 11:22:45

标签: excel vba excel-vba

我对VBA和宏很新。

我使用宏从一张纸上复制并粘贴到下一张可用列中的另一张纸上。这很棒,正是我想要的,但我需要它作为值粘贴。我已经尝试过每个人都说过但仍然没有运气的事情。

我需要做出哪些改变?

Sub HistoricalData()
Dim TargetSht As Worksheet, SourceSht As Worksheet, SourceCol As Integer, SourceCells As Range

'If an error occurs skip code to the Err-Hanlder line and the display the error message.
On Error GoTo Err_Handler

'This is the sheet where your copy information from. Change "Sheet1" to the name of your soure sheet
Set SourceSht = ThisWorkbook.Sheets("BARGE LIVE TRACKING")

'Name of the sheet where data is to be copied to. Rename Sheet2 to the name of your target sheet
Set TargetSht = ThisWorkbook.Sheets("Sheet9")

'This is the cells you will copy data from. This is targeting cells B1 to the last used cell in column B
Set SourceCells = SourceSht.Range("I3:I" & SourceSht.Range("I65536").End(xlUp).Row)

'This is finding the next column available in the target sheet. It assumes dates will be in row 1 and data in row 2 down
If TargetSht.Range("A1").Value = "" Then
    'Cell A1 is blank so the column to put data in will be column #1 (ie A)
    SourceCol = 1
ElseIf TargetSht.Range("IV1").Value <> "" Then
    'Cell IV1 has something in it so we have reached the maximum number of columns we can use in this sheet.
    'Dont paste the data but advise'
    MsgBox "There are no more columns available in the sheet " & TargetSht.Name, vbCritical, "No More Data Can Be Copied"
    'stop the macro at this point
    Exit Sub
Else
    'cell A1 does have data and we havent reached the last column yet so find the next available column
    SourceCol = TargetSht.Range("IV1").End(xlToLeft).Column + 1
End If

'Put in the date in the appropriate column in row 1 of the target sheet
TargetSht.Cells(1, SourceCol).Value = Format(Date, "DD/MM/YYYY")

'We can now start copying data. This will copy the cells in column B from the source sheet to row 2+ in the target sheet
SourceCells.Copy TargetSht.Cells(2, SourceCol)

'Advise the user that the process was successful
MsgBox "Data copied successfully!", vbInformation, "Process Complete"

Exit Sub 'This is to stop the procedure so we dont display the error message every time.

Err_Handler:
MsgBox "The following error occured:" & vbLf & "Error #: " & Err.Number & vbLf & "Description: " & Err.Description, _
        vbCritical, "An Error Has Occured", Err.HelpFile, Err.HelpContext


End Sub

1 个答案:

答案 0 :(得分:0)

作为一般规则,您始终可以使用&#34;记录宏&#34;来记录您的步骤。这是帮助您了解VBA细节的绝佳方式。

如果您没有在Excel工具栏上看到开发人员标签,则可以了解如何展示HERE.

在开发人员选项卡上,单击记录宏。它会要求你命名宏,但会给它命名为Macro1,这很好。录制时,突出显示要从中复制值的公式单元格并复制(cntrl-C或右键单击 - 复制)。

然后选择另一个单元格开始粘贴。右键单击该单元格,然后选择&#34;选择性粘贴。&#34;然后选择&#34;值&#34;并且只会粘贴值。然后单击“停止录制”。

然后转到VBA编辑器并在模块中查找宏。您会发现user3598756的答案是正确的。这是一种非常简单的方法来教自己excel的基本功能。