将数组打印到工作表上

时间:2018-12-16 16:43:34

标签: arrays excel vba

我对VBA完全陌生,并且存在以下问题:

我需要创建一个宏,该宏将前10个偶数的数组打印到工作表上。

我提出了以下内容,但我不知道如何将其实际打印到工作表上(即最后一步)。有人可以帮忙吗?

Sub FirstTenEvenNumbers()
Dim a(1 To 10) As Integer

a(1) = 2
a(2) = 4
a(3) = 6
a(4) = 8
a(5) = 10
a(6) = 12
a(7) = 14
a(8) = 16
a(9) = 18
a(10) = 20

End Sub

谢谢!

4 个答案:

答案 0 :(得分:4)

您可以使用数组维度的上界直接写入工作表(如果要作为行,请使用转置)

Public Sub FirstTenEvenNumbers()
    Dim a(1 To 10) As Integer

    a(1) = 2
    a(2) = 4
    a(3) = 6
    a(4) = 8
    a(5) = 10
    a(6) = 12
    a(7) = 14
    a(8) = 16
    a(9) = 18
    a(10) = 20

    ActiveSheet.Range("A1").Resize(UBound(a), 1) = Application.Transpose(a) 'rows
    ActiveSheet.Range("C1").Resize(1, UBound(a)) = a 'columns
End Sub

答案 1 :(得分:2)

将数组粘贴到范围中

Sub FirstTenEvenNumbers()

  Const cVntName As Variant = "Sheet1"    ' Worksheet Name/Index
  Const cStrRange As String = "A1"        ' Paste Range
  Const cIntNum As Integer = 10           ' Number of Values

  Dim vntNum As Variant                   ' Array of Values
  Dim intCount As Integer                 ' Values Counter, Array Rows Counter

  ' Resize the array to a one-column one-based two-dimensional array.
  ' The first 1 means one-base and the cIntNum is the size of the first
  ' dimension, the upper bound (UBound).
  ' The second 1 means the second dimension is one-based and the last 1 one
  ' means one column.
  ' This array is purposly constructed in this way to be able to paste it
  ' into a range.
  ReDim vntNum(1 To cIntNum, 1 To 1)

  ' Loop through the values.
  For intCount = 1 To cIntNum
  ' Write calculated results (2 * intCount) to array (vntNum).
    vntNum(intCount, 1) = 2 * intCount
  Next


  With ThisWorkbook.Worksheets(cVntName)
  ' Resize the cell range to the size of the array and paste they array into it.
    .Range(cStrRange).Resize(UBound(vntNum), 1) = vntNum
  End With

End Sub

答案 2 :(得分:0)

简单

ActiveSheet.Cells( y, x ).Value = n

其中y是行索引,x是列索引,n是必须将单元格设置为的值。

要实现所需的功能,为什么不使用for循环?

Sub FirstTenEvenNumbers()
    for i = 1 to 10
        ActiveSheet.Cells( i, 1 ).Value = i * 2
    next i
End Sub  

答案 3 :(得分:0)

您可以使用Excel ROW()函数:

from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
def build_classifier():
  classifier = Sequential()
  classifier.add(Dense(units = 6 , init='uniform' , activation= 'relu'))
  classifier.add(Dense(units = 6 , init='uniform' , activation= 'relu'))
  classifier.add(Dense(units = 1 , init='uniform' , activation= 'sigmoid'))
  classifier.compile(optimizer='adam' , loss = 'binary_crossentropy' , 
  metrics=['accuracy'])
  return classifier
KC = KerasClassifier(build_fn=build_classifier)
parameters = {'batch_size' : [25,32],
          'epochs' : [100,500],
          'optimizer':['adam','rmsprop']}
grid_search = GridSearchCV(estimator=KC , 
param_grid=parameters,scoring='accuracy',cv=10)
grid_search.fit(X_train,y_train)

通过简单的操作,粘贴范围应从偶数行开始