如何在Cells()。Select命令中将单元格的值设置为其中包含公式的单元格的值?

时间:2019-02-13 19:38:01

标签: excel vba

我正在尝试创建一个宏,该宏将工作表的某些单元格中的值复制并粘贴到工作表2中。

这是我在单元格“ AI2”中编写的公式:

=IFERROR(SUM(1+AH:AH),"0")

并生成一个我想在宏中用作可变行坐标的数字。

这是我在工作表中为了触发宏而使用的代码:

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
     If Range("AI2") <> 0 Then
     Call macro1
     End If
End Sub

这是宏:

Sub macro1()
Dim RV As Integer
RV = Sheets("sheet1").Range("AI2").Value
Cells(RR, 33).Select
Range(ActiveCell.Offset(0, -6), ActiveCell.Offset(0, -1)).Select
Selection.Copy
Sheets("sheet2").Select
Range("A1048576").Select
Selection.End(xlUp).Select
ActiveCell.Offset(1, 0).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
End Sub

如果我删除了代码的前三行,那么宏可以工作,但是我必须手动选择要引用的偏移量的单元格。

我需要这样做,以便将单元格“ AI2”的值用作此代码行中的第一个坐标:

Cells(RR, 33).Select

我对任何一种编程都非常陌生,但是我想学习这一点,以便实现此电子表格以及具有类似功能的电子表格的目标。

2 个答案:

答案 0 :(得分:1)

我将您的Worksheet_Change的范围限制为仅在Column AH中注册了更改时才触发,因为这是将触发Column AI中的公式更改的列


Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 34 Then
        If Range("AI2") <> 0 Then
            Macro2
        End If
    End If
End Sub

Sub Macro2()

Dim cs As Worksheet: Set cs = ThisWorkbook.Sheets("Sheet1")
Dim ps As Worksheet: Set ps = ThisWorkbook.Sheets("Sheet2")

Dim xRow As Long, LR As Long
LR = ps.Range("A" & ps.Rows.Count).End(xlUp).Offset(1).Row
xRow = cs.Range("AI2").Value

cs.Range(cs.Cells(xRow, "AB"), cs.Cells(xRow, "AG")).Copy
    ps.Range("A" & LR).PasteSpecial xlPasteValues

End Sub

答案 1 :(得分:0)

将范围复制到第一个空单元格

计算

如果您在单元格区域2019-02-13 12:31:58.622 18514-18514/com.example.macyg.androidmediaplayer E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.macyg.androidmediaplayer, PID: 18514 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/document/12 flg=0x1 }} to activity {com.example.macyg.androidmediaplayer/com.example.macyg.androidmediaplayer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference at android.app.ActivityThread.deliverResults(ActivityThread.java:4360) at android.app.ActivityThread.handleSendResult(ActivityThread.java:4402) at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249) at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182) at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520) at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191) at com.example.macyg.androidmediaplayer.GetMetaData.getInit(GetMetaData.java:46) at com.example.macyg.androidmediaplayer.GetMetaData.metaRetriver(GetMetaData.java:21) at com.example.macyg.androidmediaplayer.MainActivity.onActivityResult(MainActivity.java:110) at android.app.Activity.dispatchActivityResult(Activity.java:7454) at android.app.ActivityThread.deliverResults(ActivityThread.java:4353) at android.app.ActivityThread.handleSendResult(ActivityThread.java:4402)  at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)  at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)  at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:193)  at android.app.ActivityThread.main(ActivityThread.java:6669)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)  中使用公式,则应该使用每次在计算公式时都会发生的工作表计算事件。< / p>

标准模块

AI2

Sheet1

Option Explicit

Public Const strRange As String = "AI2"
Public vntValue As Variant

Sub macro1()

    Dim rng As Range  ' Target Cell Range
    Dim RV As Long    ' Row Value

    ' In Target Worksheet
    With ThisWorkbook.Sheets("Sheet2")
        ' Calculate the first empty (unused) cell in column A (A1 not included).
        Set rng = .Cells(.Rows.Count, "A").End(xlUp).Offset(1)
    End With

    ' In Source Worksheet
    With ThisWorkbook.Worksheets("Sheet1")
        ' Write the value of Row Cell to Row Value.
        RV = .Range(strRange).Value
        With .Cells(RV, "AH") ' or 33
            ' Copy range from "AB" to "AG" in row defined by Row Value in
            ' Source Worksheet to the range from "A" to "F" in row of Target
            ' Cell Range in Target Worksheet.
            rng.Resize(, 6) = Range(.Offset(0, -6), .Offset(0, -1)).Value
        End With
    End With

End Sub

此工作簿

Option Explicit

Private Sub Worksheet_Calculate()
    If vntValue <> Range(strRange).Value Then
        vntValue = Range(strRange).Value
        If Range(strRange).Value <> "0" Then macro1
    End If
End Sub

更改

如果您要手动更改单元格区域Option Explicit Private Sub Workbook_Open() vntValue = Worksheets("Sheet1").Range(strRange).Value End Sub 中的值,则必须使用工作表更改事件。

标准模块

AI2

Sheet1

Option Explicit

Sub macro1()

    Dim rng As Range  ' Target Cell Range
    Dim RV As Long    ' Row Value

    ' In Target Worksheet
    With ThisWorkbook.Sheets("Sheet2")
        ' Calculate the first empty (unused) cell in column A (A1 not included).
        Set rng = .Cells(.Rows.Count, "A").End(xlUp).Offset(1)
    End With

    ' In Source Worksheet
    With ThisWorkbook.Worksheets("Sheet1")
        ' Write the value of Row Cell to Row Value.
        RV = .Range("AI2").Value
        ' In cell at the intersection of Row Value and column "AH".
        With .Cells(RV, "AH") ' or 33
            ' Copy range from "AB" to "AG" in row defined by Row Value in
            ' Source Worksheet to the range from "A" to "F" in row of Target
            ' Cell Range in Target Worksheet.
            rng.Resize(, 6) = Range(.Offset(0, -6), .Offset(0, -1)).Value
        End With
    End With

End Sub

Calculate 版本类似,您可能还希望使用公共变量(Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) Const cCell As String = "AI2" If Target = Range(cCell) Then If Range(cCell).Value <> "0" Then macro1 End If End Sub )来防止在单元格区域{{1 }}并没有真正改变。