在单独的子例程中将子例程的输出用作变量

时间:2018-10-05 17:57:57

标签: excel vba excel-vba

基本上我在这里要做的就是使用这个子:

Sub SelectFirstBlankCell()
Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String

sourceCol = ActiveCell.Column   'Uses ActiveCell.Column as reference now, but needs to fit into each Subroutine to select next available
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

'for every row, find the first blank cell and select it
For currentRow = 1 To rowCount
    currentRowValue = Cells(currentRow, sourceCol).Value
    If IsEmpty(currentRowValue) Or currentRowValue = "" Then
        Cells(currentRow, sourceCol).Select
        Exit For
    End If
Next
End Sub

要查找列中的下一个空单元格,以将该子行中的字符串输入。

Set selRange = Selection

For i = 0 To ListBox1.ListCount - 1
  If ListBox1.Selected(i) = True Then
     If strApps = "" Then
      strApps = ListBox1.List(i)
      intAppCodeOffset = i
      strAppCodeVal = Worksheets("TestSheet").Range("B31").Offset(i, 0).Value
    Else
      strApps = strApps & ", " & ListBox1.List(i)
      intAppCodeOffset = i
      strAppCodeVal = strAppCodeVal & ", " & Worksheets("TestSheet").Range("B31").Offset(i, 0).Value
    End If
  End If
Next

Set selRange = selRange.Offset(1, 0)

With selRange
  selRange.Value = strAppCodeVal
End With

我尝试将selRage.Offset(1, 0)替换为SelectFirstBlankCell,但是每次都会收到对象引用错误。在此方面的任何帮助将不胜感激,因为我似乎在这里找不到如何做。

1 个答案:

答案 0 :(得分:0)

如上面的评论中所述,请尝试将Sub更改为Function,如下所示:

Function SelectFirstBlankCell(sourceCol as Integer) as Range

(删除旧的sourceCol暗淡和分配)

...
        Set SelectFirstBlankCell = Cells(currentRow, sourceCol)
...
End Function

然后您可以进行更改:

Set selRange = SelectFirstBlankCell(ActiveCell.Column) 'Or whatever you think should be defined as the sourceCol

您的代码可能自己不应选择任何内容,除非那是宏的最终结果。尝试使用代码直接操作单元格。