首页 > 解决方案 > 我需要一种方法将未知的最后一个单元格与其他单元格连接起来,并使用带有前导零的格式

问题描述

我尝试使用 number.format = "00000000000000000" 作为单元格,但它没有与前导零连接

Range("A" & Cells(Rows.Count, 1).End(xlUp).Row + 1).Formula = "=(" & Range("A" & Cells(Rows.Count, 1).End(xlUp).Row) & ")&(" & text(" & Range("B" & Cells(Rows.Count, 1).End(xlUp).Row) & "),00000000000000000)"

我希望单元格与预期的格式连接,但我有 Comile 错误

标签: excelvba

解决方案


最好与Objects和一起使用Variables。您的代码变得干净且易于管理。

这是你正在尝试的吗?

Sub Sample()
    Dim ws As Worksheet
    Dim lrow As Long
    Dim sFormula As String

    Set ws = Sheet1 '<~~ Change this to the relevant sheet

    With ws
        lrow = .Cells(.Rows.Count, 1).End(xlUp).Row

        sFormula = "=A" & lrow & "&TEXT(B" & lrow & ",""00000000000000000"")"

        .Range("A" & lrow + 1).Formula = sFormula
    End With
End Sub

如果 Col A 和 Col B 的最后一行不同,则使用此代码

Sub Sample()
    Dim ws As Worksheet
    Dim lrowA As Long, lrowB As Long
    Dim sFormula As String

    Set ws = Sheet1

    With ws
        lrowA = .Cells(.Rows.Count, 1).End(xlUp).Row '<~~ Col A Last Row
        lrowB = .Cells(.Rows.Count, 2).End(xlUp).Row '<~~ Col B Last Row

        sFormula = "=A" & lrowA & "&TEXT(B" & lrowB & ",""00000000000000000"")"

        .Range("A" & lrowA + 1).Formula = sFormula
    End With
End Sub

推荐阅读