Passing value to excel inputbox from VB.NET

前端 未结 2 965
野的像风
野的像风 2020-12-06 02:04

I am trying to automate data population on some excel sheets that have some macros. Now the excel is protected and I cannot get the secret key. Now I am able to run the macr

2条回答
  •  不知归路
    2020-12-06 02:51

    Currently, I employ a method where I run a thread before the macro is called by the script. The thread checks if the inputbox has been called. If it is, it picks up the value from the location and using sendkeys, submits the box.

    This is a rudimentary solution but I was hoping for a more elegant solution to this problem.

    My solution Code:

    Public Class Form1
        Dim excelApp As New Excel.Application
        Dim excelWorkbook As Excel.Workbook
        Dim excelWorkSheet As Excel.Worksheet
    
        Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
            excelWorkbook = excelApp.Workbooks.Open("D:/excelSheets/some_excel.xls")
            excelApp.Visible = True
    
            excelWorkSheet = excelWorkbook.Sheets("SheetName")
    
            With excelWorkSheet
                .Range("B7").Value = "Value"
            End With
    
            Dim trd = New Thread(Sub() Me.SendInputs("ValueForInputBox"))
            trd.IsBackground = True
            trd.Start()
    
            excelApp.Run("macroName")
            trd.Join()
            releaseObject(trd)
    
            excelApp.Quit()
            releaseObject(excelApp)
            releaseObject(excelWorkbook)
        End Sub
        Private Sub releaseObject(ByVal obj As Object)
           Try
               System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
               obj = Nothing
           Catch ex As Exception
               obj = Nothing
           Finally
               GC.Collect()
           End Try
        End Sub
        Private Sub SendInputs(ByVal noOfIds As String)
            Thread.Sleep(100)
            SendKeys.SendWait(noOfIds)
            SendKeys.SendWait("{ENTER}")
            SendKeys.SendWait("{ENTER}")
        End Sub
    

提交回复
热议问题