2015-06-17 100 views
0

我在Excel中有一个二维图表。我需要使用两个字符串变量来获取单元格的值。图表看起来是这样的:获取两个字符串变量的单元格值

Document  person1 person2 
Text1  5   8 
Text2  2   1 
Text3  9   6 

网上找我发现在这之后很困难,因为:

  1. 的值是字符串,不是整数;
  2. 字符串将根据哪个人和文档组合出现而改变。

这应该是相关的唯一代码:假设文件和个人持有整数的字符串表示(是字符串变量

Dim document as string 
Dim person as string 

Dim oExcel as excel.application 
Dim oWB as workbook 
Set oExcel = New Excel.application 
Set oWB = oExcel.Workbooks.open.  ("C:") 
oExcel.Visible = True 

oWB.Sheets ("sheet1").Cells(documemt, person) 

回答

0

如文档=“1”,人=“2” )然后像

oWB.Sheets ("sheet1").Cells(val(document), val(person)) 

将工作。如果字符串变量的内容更复杂,那么您需要对这些字符串进行一些解析。

0

通过“2D图表”假设您是指工作表中的表格,并且该人员将是全文“person1”或“person2”等,并且对于文档同样如此,那么也许该函数将执行该操作。

Function FindDocPerson(person As String, document As String) As Variant 
    Const MatchExact As Integer = 0 
    Dim ws As Excel.Worksheet 
    Set ws = ActiveWorkbook.Worksheets("Sheet1") 

    Dim table As Excel.Range 
    Set table = ws.UsedRange 

    Dim docRange As Excel.Range 
    Set docRange = table.Columns(1).Offset(1, 0).Resize(table.Columns(1).Rows.Count - 1) 

    Dim personRange As Excel.Range 
    Set personRange = table.Rows(1).Offset(0, 1).Resize(1, table.Columns.Count - 1) 

    Dim personIndex As Long 
    Dim docIndex As Long 

    On Error GoTo errHandler 

    personIndex = Application.WorksheetFunction.Match(person, personRange, MatchExact) + 1 
    docIndex = Application.WorksheetFunction.Match(document, docRange, MatchExact) + 1 
    FindDocPerson = table.Cells(docIndex, personIndex).Value2 
    Exit Function 

errHandler: 
    FindDocPerson = VBA.CVErr(Excel.xlErrNA) 
End Function 

调用语法:

Dim result As Variant 
result = FindDocPerson("person2", "text1") 

If Application.WorksheetFunction.IsError(result) Then 
    ' handle it 
Else 
    ' found it 
End If 
0

有一个在你的代码一个错字,

oWB.Sheets ("sheet1").Cells(documemt, person) 

documemt应该是文件

所有,虽然一边还不清楚你想要什么要做什么,你可以多给一点描述吗?

我们所知道的是,您需要使用两个字符串变量来获取单元格的值,并且它可以是字符串或数字。你发布的代码并没有给你提供更多的暗示。

要在字符串和数字之间进行转换,可以使用CLng转换为长数字或CStr转换为字符串。如CLng函数( “3”)= 3,CStr的(3)= “3”

在您的代码如下:

Set oWB = oExcel.Workbooks.open.  ("C:") 

不工作,因为你试图打开工作簿时没有指定名称,我还注意到(“C:”)在命令调用的右侧很远,这导致我相信这是已经键入的自由式,即不在VBE中。这使解码成您的需求更加困难。

最后,此代码:

Set oExcel = New Excel.application 

你为什么从Excel VBA代码启动Excel的另一个会话?此代码是否在Excel以外的地方,例如Outlook/Access/PowerPoint/Word/Business Objects等等。

相关问题