Create string in CELL B1 from multiple rows in ColumnA

时间:2015-11-12 10:58:01

标签: sql libreoffice libreoffice-calc

I have a column in a worksheet:

ColumnA
wer
rfvg
swe
dfe

I would like to create a string 'wer','rfvg','swe','dfe' for use in a TSQL query

SELECT value
FROM table 
WHERE code IN ('wer','rfvg','swe','dfe')

What I do now:

1. put CONCATENATE("'";A1;"',") in B1
2. drag it all the way down
3. copy+ paste the generated values in ColumnB into my query

What I get is this:

SELECT value
FROM table 
WHERE code IN ('wer',
'rfvg',
'swe',
'dfe')

Since these last can contain up to 100 codes that is really annoying. I would like to create a single continuous string in cell B1.

Is there a way to do this? Thanx for thinking with me

2 个答案:

答案 0 :(得分:2)

这是一个执行此操作的宏:

Sub BuildListForQuery
    Dim oCells As Object, aCell As Object, oDoc As Object
    Dim iColumnA As Integer, sList As String
    oDoc = ThisComponent
    iColumnA = 0
    oColumn = oDoc.Sheets(0).Columns(iColumnA)
    oRanges = oDoc.createInstance("com.sun.star.sheet.SheetCellRanges")
    oRanges.insertByName("", oColumn)
    oCells = oRanges.Cells.createEnumeration
    If Not oCells.hasMoreElements Then Print "Sorry, no text to display"
    While oCells.hasMoreElements
        aCell = oCells.nextElement
        If sList = "" Then
            sList = "'" + aCell.String + "'"
        Else
            sList = sList + ",'" + aCell.String + "'"
        End If
    Wend
    aCell = oDoc.Sheets(0).getCellRangeByName("B1")
    aCell.setString(sList)
End Sub

B1的结果是'wer','rfvg','swe','dfe'

答案 1 :(得分:1)

这个怎么样:

  • 输入C1 =CONCATENATE("'",A1,"'")
  • 输入D1 =CONCATENATE(B1,",'",INDIRECT("A" & COLUMN()-2),"'")
    • COLUMN返回列的数字:A为1,B为2,等等。
    • INDIRECT接受一个字符串条目并返回单元格地址的内容,在本例中是A列中单元格的内容,行[从列号计算]。因此,列D(4)查看第2行(4 - 2),列E(5)查看第3行(5 - 2)等。
  • 将D1复制并粘贴到您想要的许多列上(100列将是CX列)
  • 放入其他单元格,我们会针对此帖子说明B3,=COUNTA(A1:A100)以显示您在A列中有多少条目
  • 在B1(您想要最终字符串的单元格)中放置公式=INDIRECT(ADDRESS(1,B3+2)) - 当然将B3替换为您实际放置COUNTA公式的位置
    • ADDRESS取(行号,列号) - 这里[第1行,列(但是A + 2列中有很多条目)]并返回一个LetterNumber单元格地址