【发布时间】:2021-05-05 17:29:37
【问题描述】:
我们有一个要求,我们的用户可以隐藏/取消隐藏和移动 Excel 列。 一旦用户单击生成 CSV 按钮,我们希望列按特定顺序排列。 例如, Col1、Col2、Col3 是 Excel 第一行 A、B、C 列中的列标题。 用户将列 Col2 移到末尾并隐藏了 Col2: A、B、C 列现在有标题:Col1、Col3、Col2(隐藏)
我们的 CSV 文件应生成为:Col1、Col2、Col3。 使用下面的代码,我们看不到 Col2,即使我们设法取消隐藏,我们怎么知道用户最后移动了 Col2?
Public Sub ExportWorksheetAndSaveAsCSV()
Dim csvFilePath As String
Dim fileNo As Integer
Dim fileName As String
Dim oneLine As String
Dim lastRow, lastCol As Long
Dim idxRow, idxCol As Long
Dim dt As String
dt = Format(CStr(Now), "_yyyymmdd_hhmmss")
' --- get this file name (without extension)
fileName = Left(ThisWorkbook.Name, InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1)
' --- create file name of CSV file (with full path)
csvFilePath = ThisWorkbook.Path & "\" & fileName & dt & ".csv"
' --- get last row and last column
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
' --- open CSC file
fileNo = FreeFile
Open csvFilePath For Output As #fileNo
' --- row loop
For idxRow = 1 To lastRow
If idxRow = 2 Then
GoTo ContinueForLoop
End If
oneLine = ""
' --- column loop: concatenate oneLine
For idxCol = 1 To lastCol
If (idxCol = 1) Then
oneLine = Cells(idxRow, idxCol).Value
Else
oneLine = oneLine & "," & Cells(idxRow, idxCol).Value
End If
Next
' --- write oneLine > CSV file
Print #fileNo, oneLine ' -- Print: no quotation (output oneLine as it is)
ContinueForLoop:
Next
' --- close file
Close #fileNo
End Sub
【问题讨论】:
-
如果标题 names 是固定的(并且只有位置不同),那么您将遍历标题以查找您想要的标题,并记下它们的位置:然后使用该信息将单元格的值写入输出文件。
-
我不是我能理解你的问题......那么,有超过三列吗?如果是,您是否只需要前三个的特定订单?如果不是,为什么要计算最后一列号?进行这样的迭代,隐藏的列单元格值也将被考虑并放置在输出的 csv 文件中。这是你需要的吗?如果是,为什么要隐藏它?如果前三列根据它们的标题排序,很明显隐藏列将是代码隐藏的列。至少,代码可以检查它。这是我想念的东西吗?你能澄清我的问题吗?
-
旁注,考虑一次抓取整行,将其转置为一维变量数组,然后使用
Strings.Join将数组中的值连接成单个字符串,而无需迭代列.第一步是确定如何判断给定列是否已移动。列有标题吗?如果是这样,它们需要位于代码中的某个位置。如果没有,...您需要不允许用户更改的标题。实际 table 中的数据是不是又名ListObject?如果是这样,这将极大地简化这里的一切。 -
您能否将标题向下移动到第 2 行并在第 1 行中使用整数来指定顺序。第 1 行可以隐藏。