首页 > 解决方案 > 仅保留循环 vba 中的第一个地址

问题描述

我有以下代码:

Dim alpha As String

Sub CopyDataDump()
Dim rSelected As Range
Dim c As Range
Dim bCol As Boolean
Dim bRow As Boolean
Dim vbAnswer As VbMsgBoxResult
Dim text As String
Dim text2 As String
Dim text3 As String
Dim First As String
Dim Second As String
Dim third As String
Dim Fourth As String
Dim ToRange As String
Dim ToBeta As String

    'Set variables
    bCol = False
    bRow = False

    'Prompt user to select cells for formula
    On Error Resume Next
    Set rSelected = Application.InputBox(prompt:= _
                    "Select Range to Copy", _
                    Title:=sTitle & " Creator", Type:=8)
    On Error GoTo 0

    'Only run if cells were selected and cancel button was not pressed
    If Not rSelected Is Nothing Then


        'Create string of cell references
        For Each c In rSelected.Cells
        alpha = c.address(bRow, bCol)
    text = c
    First = Left(text, 2)
    text2 = WorksheetFunction.Replace(text, 1, 2, "")
    Second = Left(text2, 2)
    text3 = WorksheetFunction.Replace(text2, 1, 2, "")
    third = Left(text3, 2)
    Fourth = Right(text3, 2)
    ActiveWorkbook.ActiveSheet.Range(c.address(bRow, bCol)) = Fourth & third & Second & First
        Next
    End If

    ToBeta = Replace(alpha, "A", "f")
    Application.ScreenUpdating = False
    rSelected.Copy ActiveWorkbook.Worksheets("Hex_Dump_Flash").Range(ToBeta)

End Sub

我想要做的......是在 alpha 中保留第一个地址而不是最后一个地址。它始终保留最后一个地址。如果我有 A4:A8 范围,我希望该 alpha 保留 A4 而不是 A8。

非常感谢 !

标签: vbaloops

解决方案


您正在用每个新的 c 覆盖 For Each 中的 alpha (循环时 c 成为范围中的下一个单元格)。如果不覆盖,您需要在循环之外使用它。仅获得第一个单元格使用

alpha = rSelected.Cells(1,1)

推荐阅读