注册 登录
编程论坛 VB6论坛

[求助] 求大神帮解答一下,一直不太会这个怎么用

start1901 发布于 2018-03-07 22:41, 1864 次点击
用vb6写了一个小软件,处理excel数据,中间有个过程有点复杂,就把这段写成了function,
有个问题一直很困惑:我Command1_Click()中新建的excel文件中的sheet,我想在function中with该sheet,我该怎么写??
我的写法如下,运行时提示我“  With sheets(1)”这句有变量未定义,这种functiong该怎样控制当前表格??

按钮1:
Private Sub Command1_Click()   '五、5
Dim xlApp As Excel.Application
Dim ulBook As Excel.Workbook
Dim ulSheet As Excel.Worksheet
Dim i As Integer
Dim k As Integer

Set xlApp = CreateObject("Excel.Application")
Set ulBook = xlApp.Workbooks.Add
Set ulSheet = ulBook.Worksheets(1)
'此处省略一些无用代码
With ulSheet
    For i = 8 To 12
         .Activate
         .Cells(i + 2, k) = Answer1(i, k)          'Answer1()是我的自定义方程,如下
     Next
End With

ulBook.Close (True)
xlApp.Quit
Set xlApp = Nothing
End Sub
'@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
'自定义函数
Private Function Answer1(ROW1 As Integer, COL1 As Integer)     
Dim A, AB As Double
Dim CO, i  , K As Integer

  With sheets(1)  '问题所在:根据传递的行、列两个参数,我想在这个新建的表格里做修改,怎样with到当前的sheet???

    For CO = 1 To 5
      A = .Cells(ROW1, CO+ 15) * A
    Next
 A = A * .Cells(ROW1, COL1)
 AB = .Cells(ROW1, COL1) * .Cells(ROW1+1, 5)
   End With
  Answer1 = A + AB  
End Function
4 回复
#2
HVB62018-03-08 07:33
回复 楼主 start1901
把以下3个变量定义为公共变量试试:
Dim xlApp As Excel.Application
Dim ulBook As Excel.Workbook
Dim ulSheet As Excel.Worksheet
Private Sub Command1_Click()   '五、5
'Dim xlApp As Excel.Application
'Dim ulBook As Excel.Workbook
'Dim ulSheet As Excel.Worksheet

.........
'自定义函数
Private Function Answer1(ROW1 As Integer, COL1 As Integer)     
Dim A, AB As Double
Dim CO, i  , K As Integer

 ‘ With sheets(1)  '问题所在:根据传递的行、列两个参数,我想在这个新建的表格里做修改,怎样with到当前的sheet???
With ulSheet
    For CO = 1 To 5
      A = .Cells(ROW1, CO+ 15) * A
    Next
 A = A * .Cells(ROW1, COL1)
 AB = .Cells(ROW1, COL1) * .Cells(ROW1+1, 5)
   End With
  Answer1 = A + AB  
End Function

[此贴子已经被作者于2018-3-8 07:36编辑过]

#3
xiangyue05102018-03-08 15:24
局部变量和公共变量的区别,这部分复习一下就好了
#4
start19012018-03-08 21:07
回复 2楼 HVB6
这是一个好办法,解决了我当前的问题,谢谢啊
#5
start19012018-03-10 18:23
回复 2楼 HVB6
还有一个方法,是把xlapp传递到方程中,亲测可行,我也是刚学的,分享给您
1