我正在尝试使用VS2015为我拥有的一些VBA宏创建一个Excel VSTO Addin。我可以使用VBA做到这一点,但是想要在VB.NET中沾沾自喜。我面临的问题是如何获取活动工作表并将其分配给变量。然后,我需要传入我之前转换为文本的范围。
宏本质上允许用户通过选择范围然后突出显示两个列表中显示的项目来比较两个数据列表。
这是用户尝试选择范围(工作正常)时执行的代码
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
Me.Hide()
Dim R As Microsoft.Office.Interop.Excel.Range
Dim A As String
'note how the Application.InputBox brings up different settings to just InputBox
R = Globals.ThisAddIn.Application.InputBox(Prompt:="Please select the reference range", Type:=8)
A = R.Address
Me.TextBox1.Text = A
Me.Show()
Me.TopMost = True
Exit Sub
Catch
MsgBox("Please select a valid range!")
Me.Show()
End Try
End Sub
这是“搜索和突出显示”按钮背后的代码,它应该比较两个范围并突出显示重复项。但是,当我运行它时,它突出显示不同工作簿中的单元格,可能是我打开的第一个单元格。如何确保它打开我正在操作的当前工作簿?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim xlApp As New Excel.Application
Dim ws As Excel.Worksheet
Dim sheetName As String
Dim cell_1 As Excel.Range
Dim cell_2 As Excel.Range
Dim rng_1 As Excel.Range
Dim rng_2 As Excel.Range
xlApp = GetObject(, "Excel.Application")
ws = xlApp.ActiveSheet
sheetName = ws.Name
rng_1 = ws.Range(Me.TextBox2.Text)
rng_2 = ws.Range(Me.TextBox1.Text)
For Each cell_1 In rng_1
For Each cell_2 In rng_2
If cell_2.Text = cell_1.Text Then
cell_2.Interior.ColorIndex = 6
End If
Next cell_2
Next cell_1
Me.Close()
End Sub
答案 0 :(得分:0)
您必须指定要与之交互的工作簿文件名。
Dim ExcPro as New Excel.Application
Dim Excwrkbook as Excel.Workbook=ExcPro.Workbooks.Open("YoufileName")
Dim ws As Excel.Worksheet = Excwrkbook.ActiveSheet
如果您已了解工作簿的某些详细信息(如名称),则还可以遍历工作簿集合(如果已经打开)。
Dim Exc_Books As Excel.Workbooks = Excpro.Workbooks
Dim Exc_book As Excel.Workbook = Exc_Books.Item(1)
答案 1 :(得分:0)
我找到了答案,所以我发布它是为了下次我必须搜索它。在下面的代码中,请确保将 ThisAddIn 更改为实际加载项的名称。
Dim wb As Excel.Workbook = Globals.ThisAddIn.Application.ActiveWorkbook
Dim ws As Excel.Worksheet = Globals.ThisAddIn.Application.ActiveSheet