簡體   English   中英

將單元格值與 VBA 結合

[英]Combining cell values with VBA

我的數據集有數千行,組合從 1 個單元格到 15 個單元格不等。
每個組合由一個空白單元格分隔。
我希望 VBA 在整個專欄中自動執行此過程。

第 2 列是我想要做的。
在此處輸入圖片說明

Sub Concat()
Dim i As Integer, Sht As Worksheet, Str As String
i = 3
Set Sht = ThisWorkbook.Sheets(2)
Str = Sht.Cells(2, 1).Value
Do Until Sht.Cells(i, 1).Value = "999999"
    Do Until Sht.Cells(i, 1).Value = ""
        Str = Str & "-" & Sht.Cells(i, 1).Value
        i = i + 1
    Loop
    Sht.Cells(i, 1).Value = Str

    'Here i need the string to reset and start over
    ' at the cell under the cell where stringvalue was pasted

Loop
End Sub

找到這個小代碼來連接你的前 4 個值。

Sub Concat()
    Dim i As Integer
    Dim Sht As Worksheet
    Dim Str As String
    Set Sht = ThisWorkbook.Sheets(1)
    Str = ""
    For i = 1 To 4
        Str = Str & Sht.Cells(i, 1).Value
        If Not i = 4 Then
            Str = Str & "-"
        End If
    Next i
    Sht.Cells(i, 2).Value = Str
End Sub 

在此處輸入圖片說明

從這里你可以調整它來做你所需要的。

編輯:找到代碼

Sub Concat()
    Dim i As Integer
    Dim Sht As Worksheet
    Dim Str As String
    Set Sht = ThisWorkbook.Sheets(1)
    Str = ""
    For i = 1 To Cells(Rows.Count, 1).End(xlUp).Row + 1
        If Sht.Cells(i, 1).Value = "" Then
            Str = Left(Str, Len(Str) - 1)
            Sht.Cells(i, 2).Value = Str
            Str = ""
        Else
            Str = Str & Sht.Cells(i, 1).Value & "-"
        End If
    Next i
End Sub
Sub Concat_numbers()

Dim i As Integer, Sht As Worksheet, Str As String
i = 3
Set Sht = ThisWorkbook.Sheets(1)
Str = Sht.Cells(2, 1).Value

Do Until Sht.Cells(i, 1).Value = "999999"


Do Until Sht.Cells(i, 1).Value = ""

Str = Str & "-" & Sht.Cells(i, 1).Value
i = i + 1
Loop


Sht.Cells(i, 2).Value = Str

i = i + 1
Str = Sht.Cells(i, 1).Value
i = i + 1

Loop

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM