以字符串(VBA)的形式获取Excel工作表中的所有单元格

时间:2011-06-28 19:33:10

标签: vba excel-vba excel

基本上我正在创建一个excel应用程序,在运行时,会提示用户指向一个特定的excel文件,它会将该位置作为字符串,工作正常。我不知道该怎么做是在活动工作表中选择一个范围并取每个单元格中的值并将它们组合成1个字符串。

到目前为止,这是我的代码:

Option Explicit

Sub locate_file()

Dim file As String
Dim sheet1_95 As String
Dim theRange As Range

'prompt user for location of other excel sheet'
file = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx")

'test input of location'
Workbooks("testing input file.xlsx").Sheets("location").Activate
Range("A1") = file

'activate the workbook and sheet'
Workbooks("95%.xlsx").Sheets("DT").Activate

'Testing retrieving cells as string'
Set theRange = Range("A2:A4")

'how do i retrieve values in this range and combine them into 1 string?'

End Sub

2 个答案:

答案 0 :(得分:2)

  

我不知道该怎么办是在活动工作表中选择一个范围

使用Application.InputBox函数(而不是VBA.InputBox):

dim r as range
set r = application.inputbox("Select a range", Type:=8)

  

并获取每个单元格中的值并将它们组合成1个字符串。

循环遍历细胞:

dim c as range
dim s as string

for each c in r.cells
  s = s & c.value
next

答案 1 :(得分:2)

'Testing retrieving cells as string'
Set theRange = Range("A2:A4")

'how do i retrieve values in this range and combine them into 1 string?'
Dim c as int, x as int
Dim strValue as string
c = therange.rows.count
strValue = vbnullstring
for x = 1 to c
strValue = strValue & theRange.cells(x,1).value
next x