excel 将地址格式从回车格式更改为逗号分隔格式?

92dk7w1h  于 2023-08-08  发布在  其他
关注(0)|答案(2)|浏览(193)

因此,我有客户下订单,并以典型的回车格式发送地址,例如。

Foo Bar
100 Main St
Apt #4
New York
NY 
10001

字符串
我需要的格式自动转换为逗号分隔格式:
Foo Bar,100 Main St,Apt #4,约克,美国
如果公寓/套房号码丢失,则在这两个逗号之间为空白,例如。
Foo Bar 100 Main St,纽约,美国
逗号分隔的原因是因为它被粘贴到Excel CSV文件中。有没有办法自动将回车格式转换为逗号分隔格式?数据量相同(姓名、地址、公寓/套房、城市、州、邮政编码。
这将是一个巨大的帮助,我认为它需要VBA。谢谢你,谢谢
这些值需要位于Excel csv文件的不同列中。每个部分(姓名,地址,套房/公寓,城市,州,邮编)。

编辑:请让我知道如果需要任何其他信息

mzsu5hc0

mzsu5hc01#

创建临时工作簿。向下扫描输入数据,将每行复制到新工作簿中的相应列。然后保存为CSV并关闭临时工作簿。

Option Explicit

Sub CreateCSV()

   Const CSVNAME = "clients.csv"
   
   Dim wbCSV As Workbook, wsCSV As Worksheet, rCSV As Long
   Dim lastrow As Long, r As Long, c As Long, n As Long
   Dim CSVfullname As String, ar
   
   ' temp workbook to save as CSV
   Set wbCSV = Workbooks.Add(1)
   Set wsCSV = wbCSV.Sheets(1)
   
   'scan addresses
   With ThisWorkbook.Sheets(1)
       lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
       
       r = 1
       Do While r <= lastrow
            If Len(.Cells(r, 1)) = 0 Then
                r = r + 1
            Else
                ' copy next 6 lines to csv sheet
                rCSV = rCSV + 1
                For c = 1 To 4
                    If c = 4 Then
                        ' split 4th line into 3 columns
                        ar = Split(.Cells(r, 1), ",")
                        For n = 0 To UBound(ar)
                            wsCSV.Cells(rCSV, c + n) = ar(n)
                        Next
                    Else
                        wsCSV.Cells(rCSV, c) = .Cells(r, 1)
                    End If
                    r = r + 1
                Next
          End If
       Loop
   End With
   
   ' save temp workbook
   CSVfullname = ThisWorkbook.path & "\" & CSVNAME
   wbCSV.SaveAs CSVfullname, FileFormat:=xlCSV
   wbCSV.Close savechanges:=False
   
   ' result
   MsgBox rCSV & " records saved to " & CSVfullname, vbInformation
End Sub

字符串

tgabmvqs

tgabmvqs2#

我相信有更干净的方法,但这是一个简单的方法。复制地址'的范围(假设公寓不存在,则有一个单元格为空),然后将其转置(注意:不能在复制区域的顶部转置)。删除原始复制的地址,并根据需要拆分城市、州和邮编。

Private Sub tester()
    Dim ws As Worksheet
    Set ws = Worksheets("test")
    Dim rng As Range
    Set rng = ws.Range("A1:A4")
    Dim pasted As Range
    Set pasted = ws.Range("B1")
    
    Dim parts() As String
    Dim temp As String
    Dim i As Integer
    
    rng.Copy
    ws.Range("B1:E1").PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=True, _
    Transpose:=True
    rng.ClearContents
    
    temp = Replace(pasted.Offset(0, 3).Value, ",", "")
    parts = Split(temp, " ")
    
    For i = 0 To UBound(parts)
        pasted.Offset(0, i + 3) = parts(i)
    Next i
    
    If pasted.Offset(0, 2).Value = "" Then
        pasted.Offset(0, 2).Delete
    End If
    
End Sub

字符串
编辑:重写代码以适用于场景

相关问题