我想知道为什么我会遇到这个问题。
Private Sub test()
Dim Row As Integer
For Row = 1 To 100
'Loop through SummaryRange and ignore blanks but get document type'
Dim documentTypes As String
Dim myDocument As String, Column As Integer
Column = 2
'First get range from Summary'
Sheets("Sheet1").Active
If ActiveSheet.Cells(Row, Column).Value <> "" Then documentTypes = documentTypes + "," + ActiveSheet.Cells(Row, Column).Value
Sheets("Sheet12").Active
ActiveSheet.Range("B17").Value = documentTypes
Next Row
End Sub
我试图在不同的工作表中循环一个范围,然后获取值,然后将它们连接成一个字符串并输出该字符串。
编辑:
删除了SummaryRange,摆脱了范围问题,但却出现了Object doesn't support this property or method
答案 0 :(得分:1)
尝试更改
SummaryRange.Range("Row:Column").Value
到
SummaryRange.Range(Row:Column).Value
更新:尝试以下
Dim range As Range
Dim row As Range
Dim cell As Range
Set range = Range("B1:B100")
For Each row In range.Rows
For Each cell in row.Cells
'processing code
'documentTypes = documentTypes + "," + cell.Value
'etc...
Next cell
Next row
答案 1 :(得分:1)
尝试更改:
Sheets("Sheet1").Active
要:
Sheets("Sheet1").Activate
同样如此:
Sheets("Sheet12").Active
答案 2 :(得分:1)
虽然bouvierr已经解答了您现有的问题,但我注意到您实际上可以避免循环并更有效地执行此操作
这一行
strOut = Join(Application.Transpose(ws.Range("B1:B100")), ",")
从B1:B100生成一个由逗号分隔的所有值的字符串
由于某些值可能为空,因此生成的字符串可能看起来像这样
test,1,2,3,,,3,,afaff,,,,,,,,,,,
所以我使用正则表达式将多个,
清理为一个'
Sub QuickGrab()
Dim ws As Worksheet
Dim objRegex
Dim strOut As String
Set ws = Sheets("Sheet1")
strOut = Join(Application.Transpose(ws.Range("B1:B100")), ",")
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = ",{2,}"
.Global = True
strOut = .Replace(strOut, ",")
End With
MsgBox strOut
End Sub