【发布时间】:2015-11-27 14:12:46
【问题描述】:
如何在 Visual Basic 中从 B 列读取 Excel 单元格中的“控件”表格直到单元格为空?
之后,我想为每个单元格生成一个新工作表,其名称来自单元格。在此:
您会看到本专栏的内容,有时可能会有所不同。读完后,我想生成名称为:RW_BONDS, ... .
【问题讨论】:
如何在 Visual Basic 中从 B 列读取 Excel 单元格中的“控件”表格直到单元格为空?
之后,我想为每个单元格生成一个新工作表,其名称来自单元格。在此:
您会看到本专栏的内容,有时可能会有所不同。读完后,我想生成名称为:RW_BONDS, ... .
【问题讨论】:
你可以这样做。
Private Sub CommandButton1_Click()
Dim ws As Excel.Worksheet
Dim lRow As Long
Dim lastRow As Long
'Set the sheet to read from
Set ws = Application.Sheets("control")
'Set the row to start reading at
lRow = 3
lastRow = wsOwners.Cells(wsOwners.Rows.Count, "B").End(xlUp).Row
'Loop through the rows
Do While lRow <= lastRow
If ws.Range("B" & lRow).Value <> "" then
'Add a new sheet
ActiveWorkbook.Sheets.Add Before:=Worksheets(Worksheets.Count)
'Change the name to the value of column B in the current row
ActiveWorkbook.ActiveSheet.Name = ws.Range("B" & lRow).Value
End If
'Increment your row to the next one
lRow = lRow + 1
Loop
End Sub
【讨论】:
Sub test()
Dim i As Long
i = 1
While Len(Sheets("Control").Cells(i, 2))
Worksheets.Add.Name = Sheets("Control").Cells(i, 2): i = i + 1
Wend
End Sub
编辑评论的答案:
Sub test()
Dim i As Long
i = 1
With Sheets("Control")
On Error Resume Next
Application.DisplayAlerts = False
While Len(.Cells(i, 2))
If Len(Sheets(.Cells(i, 2).Value).Name) = 0 Then Else Sheets(.Cells(i, 2).Value).Delete
Worksheets.Add.Name = .Cells(i, 2): i = i + 1
Wend
Application.DisplayAlerts = True
On Error GoTo 0
End With
End Sub
【讨论】:
i = *改成要开始的行
set ws = worksheets("Source")
row = 1
col = "B"
Do
row = row + 1
if ws.range(col & row).text = "" then exit do
worksheets.add.name = ws.range(col & row).text
Loop
End Sub
【讨论】:
Sub createSheets()
With Worksheets("control")
iRow = 1 'Start on the first row
While Len(.Cells(iRow, 2)) > 0 'While there isn't a blank cell
Worksheets.Add.Name = .Cells(iRow,2) 'Create/rename sheet
iRow = iRow + 1
Wend
End With
End Sub
【讨论】:
Worksheets.Add.Name一步完成呢?你也可以避免使用对象