如何 select 单元格范围,从第一个非黑色单元格到最后一个非空白单元格 (VBA)?
How to select range of cells, from first non-black to last non-blank cell (VBA)?
我正在尝试将表从 excel 工作簿导出到管道分隔的 txt 文件,这些文件的命名方式与相应的 sheet 相同。问题是我无法让我的宏循环访问工作簿中的不同 sheet 以将所有非空白单元格导出到 txt 文件。下面是我的代码:
Sub TableExtract()
Dim myFile As String, WS_Count As Integer, x As Integer, rng As Range, cellValue As Variant, i As Integer, j As Integer
WS_Count = ActiveWorkbook.Worksheets.Count
For x = 1 To WS_Count
myFile = "C:\Users\mohamednuri.beitelma\Desktop\" & ActiveSheet.Name & ".txt"
Set rng = Sheets(x).Range("A1").CurrentRegion
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
cellValue = rng.Cells(i, j).Value
If j = rng.Columns.Count Then
Print #1, cellValue
Else
Print #1, cellValue & "|",
End If
Next j
Next i
Close #1
Next x
End Sub
此代码returns错误。知道如何 select 第一个和最后一个非空白单元格之间范围内的所有内容,并将其导出吗?
使用当前区域属性:
Set rng = Range("A1").CurrentRegion
这相当于选择 A1
并按下 Ctrl + A
您的错误是因为您将行号和列号分配给 Range
方法,其中您应该有一个地址或 start/end 个单元格:
'// lets assume row = 5
row = Range("A" & Rows.Count).End(xlUp).row
'// lets assume col = 10
col = Cells(1, Cells.Columns.Count).End(xlToLeft).Column
'// this will produce Range(5, 10) <~~ invalid syntax
Range(row, col).Select
'// consider instead:
Set rng = Range(Cells(1, 1), Cells(row, col))
'// or use the .CurrentRegion property as mentioned above if there are no gaps in your data.
我正在尝试将表从 excel 工作簿导出到管道分隔的 txt 文件,这些文件的命名方式与相应的 sheet 相同。问题是我无法让我的宏循环访问工作簿中的不同 sheet 以将所有非空白单元格导出到 txt 文件。下面是我的代码:
Sub TableExtract()
Dim myFile As String, WS_Count As Integer, x As Integer, rng As Range, cellValue As Variant, i As Integer, j As Integer
WS_Count = ActiveWorkbook.Worksheets.Count
For x = 1 To WS_Count
myFile = "C:\Users\mohamednuri.beitelma\Desktop\" & ActiveSheet.Name & ".txt"
Set rng = Sheets(x).Range("A1").CurrentRegion
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
cellValue = rng.Cells(i, j).Value
If j = rng.Columns.Count Then
Print #1, cellValue
Else
Print #1, cellValue & "|",
End If
Next j
Next i
Close #1
Next x
End Sub
此代码returns错误。知道如何 select 第一个和最后一个非空白单元格之间范围内的所有内容,并将其导出吗?
使用当前区域属性:
Set rng = Range("A1").CurrentRegion
这相当于选择 A1
并按下 Ctrl + A
您的错误是因为您将行号和列号分配给 Range
方法,其中您应该有一个地址或 start/end 个单元格:
'// lets assume row = 5
row = Range("A" & Rows.Count).End(xlUp).row
'// lets assume col = 10
col = Cells(1, Cells.Columns.Count).End(xlToLeft).Column
'// this will produce Range(5, 10) <~~ invalid syntax
Range(row, col).Select
'// consider instead:
Set rng = Range(Cells(1, 1), Cells(row, col))
'// or use the .CurrentRegion property as mentioned above if there are no gaps in your data.