支架阻止功能运行

时间:2018-06-16 00:30:30

标签: vba variables brackets

由于括号位于何处,我很难让我的功能识别程序。

以下代码不起作用。

功能

Public Function KonKatenate(rIN As range) As String
Dim r As range
For Each r In rIN
KonKatenate = Replace(KonKatenate & r.Text, ".", "")
Next r
End Function

程序

Sub LoopThroughUntilBlanks()

Dim xrg As range

Cells(3, 951).Select
' Set Do loop to stop when two consecutive empty cells are reached.
Application.ScreenUpdating = False
i = 3
Do Until IsEmpty(ActiveCell) And IsEmpty(ActiveCell.Offset(0, -2).Value)
Cells(i, 951).Value = KonKatenate(range("AJE" & i & ":AJG" & i & ")"))
ActiveCell.Offset(1, 0).Select
i = i + 1
Loop
Application.ScreenUpdating = False
End Sub

当我完全删除括号并使用例如静态数字时,这有效:

Cells(i, 951).Value = KonKatenate(range("AJE3:AJG3"))

然而,我需要3作为变量i,以便循环超越行

非常需要建议

2 个答案:

答案 0 :(得分:2)

您的KonKatenate函数会在循环范围内时覆盖自己的结果。您需要将新的新字符串连接到结果上。你原版中没有分隔符,但我添加了一种简单的方法来包含一个分隔符。

Public Function KonKatenate(rIN As range) As String
    Dim r As range, d as string

    d = ""

    For Each r In rIN
        KonKatenate = KonKatenate & d & Replace(r.Text, ".", "")
    Next r

    KonKatenate = mid(KonKatenate, len(d)+1)

End Function

您的LoopThroughUntilBlanks子过程应该使用它声明的变量并声明它使用的变量。 A For Next循环可能更合适。

Sub LoopThroughUntilBlanks()
    dim lr as long, i as long

    Application.ScreenUpdating = False

    with activesheet    '<~~ would be better as a defined worksheet
        lr = application.max(.cells(.rows.coun, "AJO").end(xlup).row, _
                             .cells(.rows.coun, "AJO").Offset(0, -2).end(xlup).row)
        for i=3 to lr
            .Cells(i, "AJO").Value = KonKatenate(.range(.cells(i, "AJE"), .cells(i, "AJG")))
        next i
    end with

    Application.ScreenUpdating = False
End Sub

答案 1 :(得分:2)

另一种选择,没有循环

Option Explicit

Public Sub Kat_AJEtoAJG()
    Dim lrO As Long, lrM As Long

    With ThisWorkbook.Worksheets("Sheet3")       'or ThisWorkbook.Activesheet
        lrO = .Cells(.Rows.Count, "AJO").End(xlUp).Row
        lrM = .Cells(.Rows.Count, "AJM").End(xlUp).Row
        With .Range(.Cells(3, "AJO"), .Cells(IIf(lrO > lrM, lrO, lrM), "AJO"))
            .Formula = "=AJE3 & AJF3 & AJG3"
            .Value2 = .Value2
            .Replace ".", vbNullString
        End With
    End With
End Sub