Skip to content

Instantly share code, notes, and snippets.

@tdalon
Last active February 3, 2022 08:50
Show Gist options
  • Save tdalon/f1602a9e87c5842a11e1d7e74a928cb0 to your computer and use it in GitHub Desktop.
Save tdalon/f1602a9e87c5842a11e1d7e74a928cb0 to your computer and use it in GitHub Desktop.
Excel VBA Convert Table Column to Text (Csv) Only visible Cells with delimiter parameter
Function Table_ColumnToText(cCell As Range, sDelim As String)
' Get current table
Dim tblSelected As ListObject
Set tblSelected = cCell.ListObject
If tblSelected Is Nothing Then
MsgBox "Select a Table!"
TableColumnToText = "ERROR! No Table"
Exit Function
End If
Set rng = tblSelected.DataBodyRange.Columns(cCell.Column - tblSelected.HeaderRowRange.Column + 1)
TableColumnToText = ConvertToText(rng.SpecialCells(xlCellTypeVisible), sDelim)
'TableColumnToText = WorksheetFunction.TextJoin(sDelim, True, rng.SpecialCells(xlCellTypeVisible))
End Function
Function ConvertToText(rng As Range, sDelim) As String
'Function ConvertToText(Optional ByVal rng As Range = Nothing, Optional ByVal sDelim As String = ",") As String
' TextJoin could be used instead if available WorksheetFunction.TextJoin(sDelim, True, rng)
'If rng Is Nothing Then
' Set rng = Application.Selection
' Set rng = Application.InputBox("Range :", "Convert to String with Delimiter", rng.Address, Type:=8)
'End If
ConvertToText = ""
For Each cl In rng
If ConvertToText = "" Then
ConvertToText = cl.Value
Else
ConvertToText = ConvertToText & sDelim & cl.Value
End If
Next cl
End Function
Sub CopyToClipboard(Text As String)
' https://stackoverflow.com/a/25336423/2043349
'VBA Macro using late binding to copy text to clipboard.
'By Justin Kay, 8/15/2014
Dim MSForms_DataObject As Object
Set MSForms_DataObject = CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
MSForms_DataObject.SetText Text
MSForms_DataObject.PutInClipboard
Set MSForms_DataObject = Nothing
End Sub
Sub Table_ColumnToText_Macro()
Dim sDelim As String
sDelim = Application.InputBox("Enter you delimiter:", "Column2Text: Delimiter", ",", , , , , 2)
sText = Table_ColumnToText(ActiveCell, sDelim)
CopyToClipboard (sText)
End Sub
@tdalon
Copy link
Author

tdalon commented Feb 2, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment