excel - 选择表格上的行和列
问题描述
我正在使用这个脚本:
' Loop for each row in selection.
For RowCount = 1 To Selection.Rows.Count
' Loop for each column in selection.
For ColumnCount = 1 To Selection.Columns.Count
' Write current cell's text to file with quotation marks.
Print #FileNum, """" & Selection.Cells(RowCount, _
ColumnCount).Text & """";
' Check if cell is in last column.
If ColumnCount = Selection.Columns.Count Then
' If so, then write a blank line.
Print #FileNum,
Else
' Otherwise, write a comma.
Print #FileNum, ";";
End If
' Start next iteration of ColumnCount loop.
Next ColumnCount
' Start next iteration of RowCount loop.
Next RowCount
我尝试只选择范围 A1:E57
For RowCount = 1 To Range("A1:E57").EntireRow.Select
目的是,我导出此范围的修复选择。
我忘了添加什么
解决方案
范围到字符串专长ArrayList
Option Explicit
Sub testRangeToString()
Const FileName As String = "F:\Test\2021\Test.csv"
Const rgAddr As String = "A1:E57"
Const cDel As String = ";"
Const rDel As String = vbLf
Const wStr As String = """"
Dim rg As Range: Set rg = Range("A1:E57")
Dim Result As String: Result = RangeToString(rg, cDel, rDel, wStr)
Dim TextFile As Long: TextFile = FreeFile
On Error GoTo clearError
Open FileName For Output As #TextFile
Print #TextFile, Result
SafeExit:
Close #TextFile
Exit Sub
clearError:
Select Case Err.Number
Case 76
Debug.Print "Cannot create the file (" & Err.Description & ")."
Case 70
Debug.Print "The file is open (" & Err.Description & ")."
Case Else
Debug.Print "Run-time error '" & Err.Number & "': " & Err.Description
End Select
Resume SafeExit
End Sub
Function RangeToString( _
rg As Range, _
Optional ByVal ColumnDelimiter As String = ",", _
Optional ByVal RowDelimiter As String = vbLf, _
Optional ByVal WrapString As String = "") _
As String
Dim Data As Variant: Data = rg.Value
Dim rCount As Long: rCount = UBound(Data, 1)
Dim cCount As Long: cCount = UBound(Data, 2)
Dim r As Long, c As Long
Dim alr As Object: Set alr = CreateObject("System.Collections.ArrayList")
Dim alc As Object: Set alc = CreateObject("System.Collections.ArrayList")
For r = 1 To rCount
alc.Clear
For c = 1 To cCount
alc.Add WrapString & Data(r, c) & WrapString
Next c
alr.Add Join(alc.ToArray, ColumnDelimiter)
Next r
RangeToString = Join(alr.ToArray, RowDelimiter)
End Function
推荐阅读
- flask-wtforms - Flask-WTF validate_on_submit() 未执行
- javascript - 如何在 wordpress 中加速 admin-ajax.php
- python - 在 Flask 中使用外键创建堆栈
- ios - Apple Music 授权与媒体库授权
- php - PHP 和 MySQL 连接似乎工作正常,但表没有更新
- javascript - 在 React App 中重定向图像的 http get 请求
- powerbi - Power BI:在表中格式化“度量”十进制数
- scala - 在 SKUBER 中定义自定义资源
- c++ - 税收计算程序将 0.00 返回到文件的 C++ 输出流
- java - 登录时从数据库中填充 JTable