从单个单元格打印多个文本字符串

时间:2013-07-03 13:18:59

标签: excel vba loops

我目前正在使用Office 2003创建一个日历,其中包含与某些部门相关的部门代码。时间表上的每个“事件”都有自己的一组代码隐藏在每个日期旁边,我试图打印相应的字符串(每个“事件”可以有多个代码)。我需要帮助才能做到这一点。

摘要

  • dept代码在D列,从第10行开始(我是行变量)。

  • 包含这些代码的每个单元格都用逗号分隔(ex [M,A,P]) - 我希望能够根据每个部门代码单元打印多个部门名称)< / p>

  • 我对变量p的意图是找到每个部门代码的位置,以便使用vlookup。

  • 我的所有部门代码和文本字符串都在P3:Q11中找到,其中P列包含部门代码,Q列包含相应的部门名称/文本字符串。

  • p设置为每循环增加3次,因为我认为你需要跳3个字符才能找到下一个可能的部门代码(逗号,空格,新字母)。

  • 我想打印单个/多个文本字符串(取决于事件的代码是否有多个)与您查找的相应代码在同一行中,但是在列中K(与部门代码所在的位置相对 - 列D)


Sub DepartmentNames()

Dim i As Long

Dim p As Integer

Dim LastRow As Long

LastRow = Range("D" & Rows.Count).End(xlUp).Row

For i = 10 To LastRow

    For p = 1 To Len("D" & i) Step 3

        ' Placeholder

    Next

Next i

End Sub

1 个答案:

答案 0 :(得分:1)

这是我提出的解决方案,使用Split函数和集合。

Sub Reference()

' Disable screen updating
Application.ScreenUpdating = False

Dim wS As Worksheet
Set wS = ActiveSheet   ' you can change it to be a specific sheet

Dim i As Long
Dim LastRow As Long
LastRow = Range("D" & Rows.Count).End(xlUp).Row


Dim Dpts As Variant
Dim dFullText As Variant
Dim LookUp As New Collection

' Create a collection where the key is the shortcode and the value is the full name of the dpt
On Error Resume Next
For i = 3 To 11

    LookUp.Add wS.Cells(i, 17), wS.Cells(i, 16)

Next i
On Error GoTo 0


' Loop on each row
For i = 10 To LastRow

    Dpts = Split(wS.Cells(i, 4), ",") ' Split creates an array

    ' First case
    dFullText = LookUp.Item(Trim(Dpts(0)))   ' TRIM = remove trailing and leading spaces

    ' The rest of them
    For j = 1 To UBound(Dpts)

        dFullText = dFullText & ", " & LookUp.Item(Trim(Dpts(j)))

    Next j

    ' Put full text in column K
    wS.Cells(i, 11).Value = dFullText

Next i

' Enable screen updating again
Application.ScreenUpdating = True

End Sub

如果您需要澄清,请告诉我